"""REST API helpers for the terminal client."""

from __future__ import annotations

import httpx

from clients.terminal.config import settings


def _client() -> httpx.Client:
    return httpx.Client(base_url=settings.base_url, timeout=30.0)


def get_profiles() -> list[dict]:
    with _client() as client:
        resp = client.get("/agents/profiles")
        resp.raise_for_status()
        return resp.json()


def get_profile(profile_id: str) -> dict | None:
    """Return the profile dict for ``profile_id`` from /agents/profiles, or None."""
    for p in get_profiles():
        if p.get("id") == profile_id:
            return p
    return None


def get_profile_model(profile_id: str) -> str | None:
    """Configured model for a profile (first item of its priority list), or None.

    Used to show a model in the status panel before the first request resolves
    the actually-served model. ``profile.model`` is a priority list; the first
    entry is the intended model.
    """
    profile = get_profile(profile_id)
    if not profile:
        return None
    model = profile.get("model")
    if isinstance(model, list):
        return model[0] if model else None
    return model or None


def list_sessions() -> list[dict]:
    with _client() as client:
        resp = client.get("/sessions")
        resp.raise_for_status()
        return resp.json()


def create_session(profile_id: str | None = None) -> dict:
    body: dict = {}
    if profile_id:
        body["profile_id"] = profile_id
    with _client() as client:
        resp = client.post("/sessions", json=body)
        resp.raise_for_status()
        return resp.json()


def get_session(session_id: str) -> dict:
    with _client() as client:
        resp = client.get(f"/sessions/{session_id}")
        resp.raise_for_status()
        return resp.json()


def get_todos(session_id: str) -> dict:
    """Fetch the session's current todo list (GET /sessions/{id}/todos).

    Returns ``{"session_id": ..., "tasks": [{"index", "text", "status", "validation"}, ...]}``.
    Used to seed the side-panel todo on attach/switch before the first
    ``todo_updated`` WS event arrives.
    """
    with _client() as client:
        resp = client.get(f"/sessions/{session_id}/todos")
        resp.raise_for_status()
        return resp.json()


def stop_session(session_id: str) -> dict:
    with _client() as client:
        resp = client.post(f"/sessions/{session_id}/stop")
        resp.raise_for_status()
        return resp.json()
