"""Lazy loading of rich console."""

import os
from typing import Any


class LazyRichConsole:
    """Lazy loading of rich console."""

    def __init__(self, log_path: bool = True, stderr: bool = False):
        """Initialize LazyRichConsole."""
        self.log_path = log_path
        self.stderr = stderr
        self._console = None

    def _lazy_init(self):
        """Initialize _console if not yet done."""

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

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

            from rich.console import Console  # noqa: PLC0415  lazy loading of rich

            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

        if self._console is None:
            self._console = make_console(log_path=self.log_path, stderr=self.stderr)

    def print(self, *args, **kwargs):
        """Print to rich console."""
        self._lazy_init()
        self._console.print(*args, **kwargs)  # pyright: ignore[reportOptionalMemberAccess]


class DummyConsole:
    """Console that does nothing."""

    def print(self, *args, **kwargs):
        """Do nothing."""
