import os
from typing import Annotated

import typer
from rich.console import Console

_console: Console | None = None


def get_console() -> Console:
    """Get singleton Console. Checks NO_COLOR and FORCE_COLOR env vars on first call."""
    global _console
    if _console is None:
        no_color = os.environ.get("NO_COLOR", "").lower() in ("1", "true", "yes")
        force_color = os.environ.get("FORCE_COLOR", "").lower() in ("1", "true", "yes")
        if no_color:
            _console = Console(no_color=True, force_terminal=False)
        elif force_color:
            _console = Console(force_terminal=True)
        else:
            _console = Console()
    return _console


def _reset_console() -> None:
    global _console
    _console = None


class LazyConsole:
    def __getattr__(self, name: str):  # type: ignore
        return getattr(get_console(), name)


def _no_color_callback(value: bool) -> None:
    if value:
        os.environ["NO_COLOR"] = "1"
        _reset_console()


def _force_color_callback(value: bool) -> None:
    if value:
        os.environ["FORCE_COLOR"] = "1"
        _reset_console()


NoColorOption = Annotated[
    bool,
    typer.Option(
        "--no-color",
        help="Disable colored output (sets NO_COLOR=1).",
        callback=_no_color_callback,
        is_eager=True,
    ),
]
ForceColorOption = Annotated[
    bool,
    typer.Option(
        "--color",
        help="Force colored output even if not a TTY (sets FORCE_COLOR=1).",
        callback=_force_color_callback,
        is_eager=True,
    ),
]
