from __future__ import annotations

import os
import sys
from typing import Optional

try:  # pragma: no cover - optional
    from rich.console import Console
    from rich.theme import Theme
    _RICH_AVAILABLE = True
except Exception:  # noqa: BLE001
    Console = None  # type: ignore
    Theme = None  # type: ignore
    _RICH_AVAILABLE = False


_THEME = {
    "info": "bold cyan",
    "success": "bold green",
    "warning": "bold yellow",
    "error": "bold red",
}


def is_color_enabled() -> bool:
    env = os.getenv("SPEEDI_COLOR")
    if env == "0":
        return False
    if env == "1":
        return True
    # Default: enable on TTY
    try:
        return sys.stdout.isatty()
    except Exception:
        return False


class _FallbackConsole:
    def print(self, *objects, **kwargs):  # noqa: D401 - mimic rich.Console
        # Ignore style if present
        print(*objects)


_console: Optional[object] = None


def get_console():
    global _console
    if _console is not None:
        return _console
    if _RICH_AVAILABLE and is_color_enabled():  # pragma: no cover - depends on env
        theme = Theme(_THEME)
        _console = Console(theme=theme)
    else:
        _console = _FallbackConsole()
    return _console


def echo(text: str, style: Optional[str] = None) -> None:
    c = get_console()
    if _RICH_AVAILABLE and isinstance(c, Console):  # pragma: no cover
        if style:
            c.print(text, style=style)
        else:
            c.print(text)
    else:
        # Fallback ignores style
        c.print(text)


def info(text: str) -> None:
    echo(text, style="info")


def success(text: str) -> None:
    echo(text, style="success")


def warning(text: str) -> None:
    echo(text, style="warning")


def error(text: str) -> None:
    echo(text, style="error")
