from __future__ import annotations

# standard
import asyncio
from typing import Annotated

# third party
import typer

# custom
from sunwaee.config import (
    Caller,
    get_caller,
    get_default_workspace,
    get_sun_default_model,
)
from sunwaee.core.output import console
from sunwaee.core.output import error as output_error
from ..engine.factory import get_engine
from ..engine.models import list_models
from ..repl import run as run_repl
from ..session import create_session, load_session


def code(
    session_id: Annotated[
        str | None,
        typer.Option("--session", "-s", help="Resume an existing session by ID."),
    ] = None,
    model_override: Annotated[
        str | None,
        typer.Option("--model", "-m", help="Model name for this session."),
    ] = None,
) -> None:
    """Start an interactive ReAct chat session."""

    if get_caller() != Caller.USER:
        output_error("chat is only available in human mode.", "VALIDATION_ERROR")

    workspace = get_default_workspace()
    default_model, default_provider = get_sun_default_model()
    model_name = model_override or default_model
    provider = default_provider

    history = []
    if session_id:
        try:
            session, history = load_session(workspace, session_id)
        except FileNotFoundError:
            console.print(f"[red]Session {session_id!r} not found.[/red]")
            raise typer.Exit(1)
    else:
        session = create_session(workspace)

    models_cache = list_models()
    if model_override:
        found = next((m for m in models_cache if m.name == model_override), None)
        if found:
            provider = found.provider

    try:
        engine = get_engine(provider, model_name)
    except ValueError as exc:
        console.print(f"[red]{exc}[/red]")
        raise typer.Exit(1)

    asyncio.run(
        run_repl(
            session, history, engine, workspace, model_name, provider, models_cache
        )
    )
