from __future__ import annotations

# standard
import dataclasses

# third party
from rich.table import Table

# custom
from sunwaee.config import Caller, get_caller
from sunwaee.core.output import console, success
from ..engine.models import list_models


def _fmt_tokens(n: int) -> str:
    if n >= 1_000_000:
        return f"{n // 1_000_000}M"
    if n >= 1_000:
        return f"{n // 1_000}k"
    return str(n)


def _fmt_bool(v: bool) -> str:
    return "[green]✓[/green]" if v else "[red]✗[/red]"


def _fmt_price(v: float | None) -> str:
    if v is None:
        return "—"
    if v == 0:
        return "$0"
    return f"${v:.2f}".rstrip("0").rstrip(".")


def list_models_cmd() -> None:
    """List available models."""

    models = list_models()

    if get_caller() != Caller.USER:
        success([dataclasses.asdict(m) for m in models])
        return

    table = Table(show_header=True, header_style="bold")
    for col in (
        "Name",
        "Provider",
        "Context",
        "Max Out",
        "Vision",
        "Tools",
        "Thinking",
        "Th. Tokens",
        "In $/Mtok",
        "Out $/Mtok",
    ):
        table.add_column(col)

    for m in models:
        table.add_row(
            m.name,
            m.provider,
            _fmt_tokens(m.context_window),
            _fmt_tokens(m.max_output_tokens) if m.max_output_tokens else "—",
            _fmt_bool(m.supports_vision),
            _fmt_bool(m.supports_tools),
            _fmt_bool(m.supports_thinking),
            _fmt_bool(m.supports_reasoning_tokens),
            _fmt_price(m.input_price_per_mtok),
            _fmt_price(m.output_price_per_mtok),
        )

    console.print(table)
