"""Voice / text agent API: transcribe, plan, execute, email logs."""

from __future__ import annotations

import time

from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
from sqlalchemy.orm import Session

from app.agent.runner import (
    execute_actions,
    execute_from_transcript,
    plan_from_transcript,
    transcribe_audio,
)
from app.database import get_db
from app.email_service import list_email_logs
from app.schemas import (
    AgentExecuteOut,
    AgentExecuteRequest,
    AgentPlanOut,
    AgentPlanRequest,
    EmailLogOut,
    TranscribeOut,
)

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


def _read_upload(file: UploadFile) -> tuple[bytes, str]:
    data = file.file.read()
    if not data:
        raise HTTPException(400, "Empty audio file")
    return data, file.filename or "audio.webm"


def _transcribe_or_raise(data: bytes, filename: str) -> str:
    try:
        text = transcribe_audio(data, filename=filename)
    except RuntimeError as exc:
        raise HTTPException(503, str(exc)) from exc
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(502, f"Transcription failed: {exc}") from exc
    if not text:
        raise HTTPException(400, "Could not transcribe audio (empty result)")
    return text


# Plain ``def`` (not async): OpenAI calls block, so FastAPI runs these in a
# worker thread instead of freezing the event loop for every other request.
@router.post("/transcribe", response_model=TranscribeOut)
def transcribe(file: UploadFile = File(...)):
    data, filename = _read_upload(file)
    return TranscribeOut(transcript=_transcribe_or_raise(data, filename))


@router.post("/voice", response_model=AgentPlanOut)
def voice(file: UploadFile = File(...), db: Session = Depends(get_db)):
    """Audio → transcript → dry-run plan in ONE request (saves a browser round-trip)."""
    data, filename = _read_upload(file)
    t0 = time.perf_counter()
    transcript = _transcribe_or_raise(data, filename)
    t1 = time.perf_counter()
    try:
        result = plan_from_transcript(db, transcript)
    except RuntimeError as exc:
        raise HTTPException(503, str(exc)) from exc
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(502, f"Agent planning failed: {exc}") from exc
    t2 = time.perf_counter()
    result["timings_ms"] = {
        "transcribe": round((t1 - t0) * 1000),
        "plan": round((t2 - t1) * 1000),
        "total": round((t2 - t0) * 1000),
    }
    return AgentPlanOut(**result)


@router.post("/plan", response_model=AgentPlanOut)
def plan(payload: AgentPlanRequest, db: Session = Depends(get_db)):
    t0 = time.perf_counter()
    try:
        result = plan_from_transcript(db, payload.transcript)
    except RuntimeError as exc:
        raise HTTPException(503, str(exc)) from exc
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(502, f"Agent planning failed: {exc}") from exc
    timings = dict(result.get("timings_ms") or {})
    timings.setdefault("plan", round((time.perf_counter() - t0) * 1000))
    timings["total"] = round((time.perf_counter() - t0) * 1000)
    result["timings_ms"] = timings
    return AgentPlanOut(**result)


@router.post("/execute", response_model=AgentExecuteOut)
def execute(payload: AgentExecuteRequest, db: Session = Depends(get_db)):
    try:
        if payload.actions:
            result = execute_actions(
                db, payload.actions, transcript=payload.transcript
            )
        elif payload.transcript:
            result = execute_from_transcript(db, payload.transcript)
        else:
            raise HTTPException(400, "Provide transcript and/or actions")
    except HTTPException:
        raise
    except RuntimeError as exc:
        raise HTTPException(503, str(exc)) from exc
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(502, f"Agent execute failed: {exc}") from exc
    return AgentExecuteOut(**result)


@router.get("/email-logs", response_model=list[EmailLogOut])
def email_logs(limit: int = 50, db: Session = Depends(get_db)):
    return list_email_logs(db, limit=min(max(limit, 1), 200))
