"""Slices AI CLI."""

import logging
import os

from rich.console import Console

from slices_cli_ai.util.console import DummyConsole, LazyRichConsole

VERBOSITY_TRACE = 3
VERBOSITY_DEBUG = 2
VERBOSITY_INFO = 1


def make_console(*, log_path: bool = True, stderr: bool = False) -> Console:
    """Make a rich console.

    Includes workaround for special case of python via shell process inside a notebook.
    """

    res = Console(log_path=log_path, stderr=stderr)
    if not res.is_jupyter and os.getenv("JPY_SESSION_NAME") is not None:
        # We are running in a `!` shell process inside a notebook.
        # This is a special case.
        #    - This "terminal" looks interactive, but is not.
        #    - This "terminal" understand color codes, but not terminal control codes to move the cursor etc
        # We force rich to see the terminal as DUMB and non-interactive
        # Also, we make sure we don't revert to default dumb terminal size,
        #    which is very small, so we set fallbacks for LINES and COLUMNS
        os.environ["TERM"] = "DUMB"
        return Console(
            log_path=log_path,
            stderr=stderr,
            force_interactive=False,
            width=int(os.getenv("COLUMNS") or 140),
            height=int(os.getenv("LINES") or 30),
        )
    return res


console = make_console(log_path=False)
err_console = make_console(stderr=True)


DEBUG_LEVEL_INFO = 1
DEBUG_LEVEL_DEBUG = 2
DEBUG_LEVEL_TRACE = 3

try:
    DEBUG_LEVEL = int(os.environ.get("SLICES_DEBUG", "0"))
except ValueError:
    DEBUG_LEVEL = 0
    err_console.print("[red bold] :x: ignoring SLICES_DEBUG environment variable: not an integer", highlight=False)

console_info = LazyRichConsole(log_path=False) if DEBUG_LEVEL >= DEBUG_LEVEL_INFO else DummyConsole()
console_debug = LazyRichConsole(log_path=False) if DEBUG_LEVEL >= DEBUG_LEVEL_DEBUG else DummyConsole()
console_trace = LazyRichConsole(log_path=False) if DEBUG_LEVEL >= DEBUG_LEVEL_TRACE else DummyConsole()


class RichConsoleHandler(logging.Handler):
    """Rich console handler."""

    def emit(self, record: logging.LogRecord) -> None:
        """Emit a record."""
        if record.levelno >= logging.WARNING and DEBUG_LEVEL >= DEBUG_LEVEL_INFO:
            console_info.print(f"[yellow bold]{record.getMessage()}", highlight=False)
        elif record.levelno >= logging.INFO and DEBUG_LEVEL >= DEBUG_LEVEL_DEBUG:
            console_info.print(f"[blue]{record.getMessage()}", highlight=False)
        elif record.levelno >= logging.DEBUG and DEBUG_LEVEL >= DEBUG_LEVEL_TRACE:
            console_debug.print(f"[bright_black]{record.getMessage()}", highlight=False)


def handle_logging(logger_name: str):
    """Set up logging for the given logger.

    The logging will be done by using the appropriate console.
    This console can be a rich console or a dummy console depending on the SLICES_DEBUG environment variable.
    """
    slices_clientlib_core_logger = logging.getLogger(logger_name)
    if DEBUG_LEVEL <= DEBUG_LEVEL_TRACE:
        slices_clientlib_core_logger.setLevel(logging.DEBUG)
    elif DEBUG_LEVEL <= DEBUG_LEVEL_DEBUG:
        slices_clientlib_core_logger.setLevel(logging.INFO)
    elif DEBUG_LEVEL <= DEBUG_LEVEL_INFO:
        slices_clientlib_core_logger.setLevel(logging.WARNING)
    slices_clientlib_core_logger.addHandler(RichConsoleHandler())


handle_logging("slices_clientlib_core")
handle_logging("slices_clientlib_aiis")
handle_logging("slices_cli_ai")

# prevent any default logging from seeing our logging
logging.getLogger("slices_cli_ai").propagate = False  # Do not propagate to parent loggers
