"""Parsed trace log API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException

from mixersystem.studio.config import StudioConfig
from mixersystem.studio.formatting import fmt_duration, fmt_cost
from mixersystem.studio.log_parser import parse_trace_log
from mixersystem.studio.trace_db import has_trace_db, query_summary
from mixersystem.studio.routes import get_config
from mixersystem.studio.session_paths import resolve_session_path

router = APIRouter(prefix="/api/v1/logs", tags=["logs"])


@router.get("/{path:path}")
def get_trace_log(path: str, config: StudioConfig = Depends(get_config)):
    # Strip '/trace' suffix
    if not path.endswith("/trace"):
        raise HTTPException(status_code=400, detail="Invalid path — expected {folder}/trace")
    folder_name = path[:-len("/trace")]
    try:
        folder = resolve_session_path(config.sessions_dir, folder_name)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e)) from e
    if not folder.is_dir():
        raise HTTPException(status_code=404, detail=f"Session folder '{folder_name}' not found")

    # Prefer SQLite if available
    if has_trace_db(folder):
        summary = query_summary(folder)

        events = []
        for e in summary.events:
            events.append({
                "timestamp_utc": e.timestamp_utc,
                "event_type": e.event_type,
                "agent_name": e.agent_name,
                "call_id": e.call_id,
                "model": e.model,
                "mode": e.mode,
                # Formatted strings for backward compat
                "duration": fmt_duration(e.duration_secs),
                "duration_seconds": e.duration_secs,
                "cost": fmt_cost(e.cost_usd),
                "cost_usd": e.cost_usd,
                "status": e.status,
                "error_message": e.error_message,
                # New fields from SQLite
                "event_id": e.id,
                "provider": e.provider,
                "depth": e.depth,
                "duration_secs": e.duration_secs,
                "is_resume": e.is_resume,
            })

        return {
            "total_calls": summary.total_calls,
            "total_duration_seconds": round(summary.total_duration_seconds, 2),
            "total_cost_usd": round(summary.total_cost_usd, 4),
            "agents": summary.agents,
            "events": events,
            "source": "sqlite",
        }

    # Fall back to text log parsing for old sessions
    trace_path = folder / "logs" / "agent_trace.log"
    if not trace_path.is_file():
        raise HTTPException(status_code=404, detail="No trace log found")

    summary = parse_trace_log(trace_path)

    events = []
    for e in summary.events:
        events.append({
            "timestamp_utc": e.timestamp_utc,
            "event_type": e.event_type,
            "agent_name": e.agent_name,
            "call_id": e.call_id,
            "model": e.model,
            "mode": e.mode,
            "duration": e.duration,
            "duration_seconds": e.duration_seconds,
            "cost": e.cost,
            "cost_usd": e.cost_usd,
            "status": e.status,
            "error_message": e.error_message,
        })

    return {
        "total_calls": summary.total_calls,
        "total_duration_seconds": round(summary.total_duration_seconds, 2),
        "total_cost_usd": round(summary.total_cost_usd, 4),
        "agents": summary.agents,
        "events": events,
        "source": "text",
    }
