import sys
import os
import logging
from .formatters import _ColourFormatter


_MISSING = object()


def _is_docker():
    path = '/proc/self/cgroup'
    return os.path.exists('/.dockerenv') or (os.path.isfile(path) and any('docker' in line for line in open(path)))


def stream_supports_colour(stream):
    is_a_tty = hasattr(stream, 'isatty') and stream.isatty()

    if 'PYCHARM_HOSTED' in os.environ or os.environ.get('TERM_PROGRAM') == 'vscode':
        return is_a_tty

    if sys.platform != 'win32':
        return is_a_tty or _is_docker()

    return is_a_tty and ('ANSICON' in os.environ or 'WT_SESSION' in os.environ)


def setup_logging(
    *,
    handler=_MISSING,
    formatter=_MISSING,
    level=_MISSING,
    root=True,
):
    if level is _MISSING:
        level = logging.INFO

    if handler is _MISSING:
        handler = logging.StreamHandler()

    if formatter is _MISSING:
        if isinstance(handler, logging.StreamHandler) and stream_supports_colour(handler.stream):
            formatter = _ColourFormatter()
        else:
            dt_fmt = '%Y-%m-%d %H:%M:%S'
            formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')

    if root:
        logger = logging.getLogger()
    else:
        library, _, _ = __name__.partition('.')
        logger = logging.getLogger(library)

    handler.setFormatter(formatter)
    logger.setLevel(level)
    logger.addHandler(handler)
