"""Console output utilities for consistent styling."""

import os
import sys
from datetime import datetime

from rich.console import Console

# Stderr console for status messages
err_console = Console(stderr=True, highlight=False)


def _is_quiet() -> bool:
    """Check if quiet mode is enabled (SCRY_QUIET=1)."""
    return os.environ.get("SCRY_QUIET", "").lower() in ("1", "true", "yes", "on")


def _set_title(msg: str) -> None:
    """Set terminal title bar. Used in quiet mode to show progress."""
    # OSC escape sequence to set window title
    # \033]0; sets both window title and icon name
    # \007 is the bell character that terminates the sequence
    sys.stderr.write(f"\033]0;[scry-run] {msg}\007")
    sys.stderr.flush()


def _timestamp() -> str:
    """Return current time as HH:MM:SS."""
    return datetime.now().strftime("%H:%M:%S")


def status(msg: str) -> None:
    """Print a dim status message. Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(msg)
        return
    err_console.print(f"[dim]{_timestamp()} \\[scry-run][/dim] {msg}")


def info(msg: str) -> None:
    """Print an info message (cyan). Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(msg)
        return
    err_console.print(f"[dim]{_timestamp()}[/dim] [cyan]\\[scry-run][/cyan] {msg}")


def success(msg: str) -> None:
    """Print a success message (green). Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(f"✓ {msg}")
        return
    err_console.print(f"[dim]{_timestamp()}[/dim] [green]\\[scry-run][/green] {msg}")


def warning(msg: str) -> None:
    """Print a warning message (yellow)."""
    err_console.print(f"[dim]{_timestamp()}[/dim] [yellow]\\[scry-run][/yellow] {msg}")


def error(msg: str) -> None:
    """Print an error message (red)."""
    err_console.print(f"[dim]{_timestamp()}[/dim] [red]\\[scry-run][/red] {msg}")


def generating(class_name: str, attr_name: str) -> None:
    """Print a 'generating' message. Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(f"Generating {class_name}.{attr_name}...")
        return
    err_console.print(f"[dim]{_timestamp()}[/dim] [cyan]\\[scry-run][/cyan] Generating {class_name}.{attr_name}...")


def generated(class_name: str, attr_name: str) -> None:
    """Print a 'generated' success message. Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(f"✓ Generated {class_name}.{attr_name}")
        return
    err_console.print(f"[dim]{_timestamp()}[/dim] [green]\\[scry-run][/green] Generated {class_name}.{attr_name} ✓")


def using_cached(class_name: str, attr_name: str) -> None:
    """Print a 'using cached' message. Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(f"Using cached {class_name}.{attr_name}")
        return
    err_console.print(f"[dim]{_timestamp()} \\[scry-run][/dim] Using cached {class_name}.{attr_name}")


def backend_selected(backend_name: str, model: str | None, reason: str) -> None:
    """Print backend selection message. Uses title bar in quiet mode."""
    if _is_quiet():
        _set_title(f"Backend: {backend_name}")
        return
    model_str = f" (model={model})" if model else ""
    err_console.print(f"[dim]{_timestamp()} \\[scry-run][/dim] Using backend: {backend_name}{model_str} ({reason})")
