"""Document tracking API routes — cross-entity Beleg tracking."""

from __future__ import annotations

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

from tracking.document_tracker import DocumentTracker

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


class DocumentLinkRequest(BaseModel):
    chain_reference: str
    description: str | None = None
    documents: list[dict]


@router.get("/search")
async def search_documents(request: Request, q: str):
    """Search for documents across all systems by number or reference."""
    tracker = DocumentTracker(request.app.state.db)
    await tracker.ensure_tracking_tables()
    results = await tracker.search_document(q)
    return {"results": results, "count": len(results)}


@router.get("/chain/{chain_id}")
async def get_chain(request: Request, chain_id: str):
    """Get a complete document chain with all linked documents."""
    tracker = DocumentTracker(request.app.state.db)
    chain = await tracker.get_chain(chain_id)
    if not chain:
        raise HTTPException(404, "Document chain not found")
    return chain


@router.post("/link")
async def link_documents(request: Request, body: DocumentLinkRequest):
    """Create or update a document chain linking related documents."""
    tracker = DocumentTracker(request.app.state.db)
    await tracker.ensure_tracking_tables()
    return await tracker.link_documents(
        chain_reference=body.chain_reference,
        documents=body.documents,
        description=body.description,
    )


@router.post("/auto-link")
async def auto_link(request: Request):
    """Automatically find and link documents by matching reference numbers."""
    tracker = DocumentTracker(request.app.state.db)
    linked = await tracker.auto_link_by_reference()
    return {"linked_count": linked}
