"""Bibliography API — CRUD + export (BibTeX, RIS, JSON)."""

from __future__ import annotations

from fastapi import APIRouter, HTTPException, Request, Response
from pydantic import BaseModel

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


class BibEntryCreate(BaseModel):
    title: str = ""
    authors: list[str] = []
    date: str = ""
    url: str = ""
    publisher: str = ""
    doi: str = ""
    source_type: str = ""
    kb_slug: str = ""
    source_file: str = ""
    cite_key: str = ""


class BibEntryUpdate(BaseModel):
    title: str | None = None
    authors: list[str] | None = None
    date: str | None = None
    url: str | None = None
    publisher: str | None = None
    doi: str | None = None
    source_type: str | None = None


def _svc(request: Request):
    return request.app.state.bibliography_service


@router.get("")
async def list_entries(request: Request, kb: str = "", type: str = ""):
    return _svc(request).list_entries(kb=kb or None, source_type=type or None)


@router.get("/stats")
async def stats(request: Request):
    return _svc(request).stats()


@router.get("/export")
async def export(request: Request, format: str = "bibtex", kb: str = "", type: str = ""):
    svc = _svc(request)
    entries = svc.list_entries(kb=kb or None, source_type=type or None)
    if format == "bibtex":
        content = svc.export_bibtex(entries)
        return Response(
            content=content,
            media_type="text/plain",
            headers={"Content-Disposition": "attachment; filename=bibliography.bib"},
        )
    elif format == "ris":
        content = svc.export_ris(entries)
        return Response(
            content=content,
            media_type="text/plain",
            headers={"Content-Disposition": "attachment; filename=bibliography.ris"},
        )
    else:
        return entries


@router.get("/{cite_key}")
async def get_entry(request: Request, cite_key: str):
    entry = _svc(request).get_entry(cite_key)
    if not entry:
        raise HTTPException(status_code=404, detail=f"Not found: {cite_key}")
    return entry


@router.post("")
async def create_entry(request: Request, body: BibEntryCreate):
    return _svc(request).add_entry(body.model_dump(exclude_none=True))


@router.put("/{cite_key}")
async def update_entry(request: Request, cite_key: str, body: BibEntryUpdate):
    updates = body.model_dump(exclude_none=True)
    result = _svc(request).update_entry(cite_key, updates)
    if not result:
        raise HTTPException(status_code=404, detail=f"Not found: {cite_key}")
    return result


@router.delete("/{cite_key}")
async def delete_entry(request: Request, cite_key: str):
    if not _svc(request).delete_entry(cite_key):
        raise HTTPException(status_code=404, detail=f"Not found: {cite_key}")
    return {"deleted": True}
