"""Functional API routes for jobs, revisions, search, and export."""

from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter
from pydantic import BaseModel, Field

from transcription.services.library import (
    accept_revision,
    add_revision,
    export_transcripts,
    get_job_detail,
    list_jobs,
    list_revisions,
    search_accepted_transcripts,
)

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


class CreateRevisionRequest(BaseModel):
    text: str = Field(min_length=1)
    source: str = "user"
    accepted: bool = False


@router.get("/jobs")
def get_jobs() -> list[dict[str, str]]:
    jobs = list_jobs()
    return [
        {
            "id": str(job.id),
            "document_id": str(job.document_id),
            "status": job.status.value,
            "created_at": job.created_at.isoformat(),
            "updated_at": job.updated_at.isoformat(),
        }
        for job in jobs
    ]


@router.get("/jobs/{job_id}")
def get_job(job_id: UUID) -> dict[str, object | None]:
    detail = get_job_detail(job_id=job_id)
    return {
        "job": {
            "id": str(detail.job.id),
            "document_id": str(detail.job.document_id),
            "status": detail.job.status.value,
            "created_at": detail.job.created_at.isoformat(),
            "updated_at": detail.job.updated_at.isoformat(),
        },
        "document": (
            {
                "id": str(detail.document.id),
                "filename": detail.document.filename,
                "file_path": detail.document.file_path,
            }
            if detail.document is not None
            else None
        ),
        "transcript": (
            {
                "id": str(detail.transcript.id),
                "text": detail.transcript.text,
                "error_detail": detail.transcript.error_detail,
                "created_at": detail.transcript.created_at.isoformat(),
            }
            if detail.transcript is not None
            else None
        ),
        "accepted_revision": (
            {
                "id": str(detail.accepted_revision.id),
                "revision_number": detail.accepted_revision.revision_number,
                "text": detail.accepted_revision.text,
                "source": detail.accepted_revision.source,
                "created_at": detail.accepted_revision.created_at.isoformat(),
            }
            if detail.accepted_revision is not None
            else None
        ),
    }


@router.get("/jobs/{job_id}/revisions")
def get_job_revisions(job_id: UUID) -> list[dict[str, object]]:
    revisions = list_revisions(job_id=job_id)
    return [
        {
            "id": str(revision.id),
            "job_id": str(revision.job_id),
            "revision_number": revision.revision_number,
            "text": revision.text,
            "source": revision.source,
            "accepted": revision.accepted,
            "created_at": revision.created_at.isoformat(),
        }
        for revision in revisions
    ]


@router.post("/jobs/{job_id}/revisions")
def create_job_revision(job_id: UUID, payload: CreateRevisionRequest) -> dict[str, object]:
    revision = add_revision(
        job_id=job_id,
        text=payload.text,
        source=payload.source,
        accepted=payload.accepted,
    )
    return {
        "id": str(revision.id),
        "job_id": str(revision.job_id),
        "revision_number": revision.revision_number,
        "text": revision.text,
        "source": revision.source,
        "accepted": revision.accepted,
        "created_at": revision.created_at.isoformat(),
    }


@router.post("/revisions/{revision_id}/accept")
def accept_job_revision(revision_id: UUID) -> dict[str, object]:
    revision = accept_revision(revision_id=revision_id)
    return {
        "id": str(revision.id),
        "job_id": str(revision.job_id),
        "revision_number": revision.revision_number,
        "text": revision.text,
        "source": revision.source,
        "accepted": revision.accepted,
        "created_at": revision.created_at.isoformat(),
    }


@router.get("/search")
def search(query: str) -> list[dict[str, object]]:
    results = search_accepted_transcripts(query=query)
    return [
        {
            "revision_id": str(revision.id),
            "job_id": str(revision.job_id),
            "revision_number": revision.revision_number,
            "text": revision.text,
            "source": revision.source,
            "accepted": revision.accepted,
            "created_at": revision.created_at.isoformat(),
        }
        for revision in results
    ]


@router.get("/export")
def export(accepted_only: bool = True) -> dict[str, object]:
    records = export_transcripts(accepted_only=accepted_only)
    return {
        "count": len(records),
        "accepted_only": accepted_only,
        "records": records,
    }
