from __future__ import annotations

# third party
import typer
from prompt_toolkit import PromptSession

# custom
from sunwaee.config import get_sun_default_model, set_sun_default_model
from sunwaee.core.output import console
from ..engine.models import list_models
from ..repl.input import ModelCompleter


def set_model() -> None:
    """Interactively select and save the default model."""

    models = list_models()
    model_names = [m.name for m in models]
    current_model, current_provider = get_sun_default_model()
    console.print(f"  Current: [bold]{current_model}[/bold]  {current_provider}")
    console.print("  Type a model name (Tab to autocomplete, Enter to confirm)\n")

    pt = PromptSession(
        completer=ModelCompleter(model_names),
        complete_while_typing=True,
    )
    try:
        chosen = pt.prompt("  model > ").strip()
    except (EOFError, KeyboardInterrupt):
        return

    if not chosen:
        return

    found = next((m for m in models if m.name == chosen), None)
    if not found:
        console.print(f"[red]Model {chosen!r} not found.[/red]")
        raise typer.Exit(1)

    set_sun_default_model(found.name, found.provider)
    console.print(
        f"  [green]Default model set to[/green] [bold]{found.name}[/bold]  {found.provider}"
    )
