"""FastAPI router for the extraction module."""

from __future__ import annotations

from api_core.responses import ApiResponse
from api_core.router import create_api_router
from pydantic import BaseModel, Field

from extraction.models import ExtractionResult, ExtractionSchema

# ---------------------------------------------------------------------------
# Request / response bodies
# ---------------------------------------------------------------------------


class ExtractRequest(BaseModel):
    """Request body for single extraction."""

    text: str
    schema_def: ExtractionSchema = Field(..., alias="schema")
    model: str | None = None


class ExtractBatchRequest(BaseModel):
    """Request body for batch extraction."""

    texts: list[str]
    schema_def: ExtractionSchema = Field(..., alias="schema")
    model: str | None = None
    concurrency: int = Field(default=5, ge=1, le=50)


class ClassifyRequest(BaseModel):
    """Request body for text classification."""

    text: str
    categories: list[str] = Field(..., min_length=2)
    model: str | None = None


class ClassifyResponse(BaseModel):
    """Response body for text classification."""

    category: str
    confidence: float = Field(ge=0, le=1)


# ---------------------------------------------------------------------------
# Router factory
# ---------------------------------------------------------------------------


def create_extraction_router(
    service: extraction.service.ExtractionService,  # noqa: F821
) -> APIRouter:  # noqa: F821
    """Create a FastAPI router wired to the given :class:`ExtractionService`.

    The caller is responsible for constructing the ``ExtractionService`` and
    passing it here -- typically via dependency injection in the product's
    ``app.py``.

    Args:
        service: A fully-configured extraction service instance.

    Returns:
        A FastAPI ``APIRouter`` with extraction endpoints mounted.
    """
    router = create_api_router("/extract", tags=["extraction"])

    @router.post(
        "",
        response_model=ApiResponse[ExtractionResult],
        summary="Extract structured data from text",
    )
    async def extract(body: ExtractRequest) -> ApiResponse[ExtractionResult]:
        result = await service.extract(
            body.text,
            body.schema_def,
            model=body.model,
        )
        return ApiResponse(data=result)

    @router.post(
        "/batch",
        response_model=ApiResponse[list[ExtractionResult]],
        summary="Extract structured data from multiple texts",
    )
    async def extract_batch(body: ExtractBatchRequest) -> ApiResponse[list[ExtractionResult]]:
        results = await service.extract_batch(
            body.texts,
            body.schema_def,
            model=body.model,
            concurrency=body.concurrency,
        )
        return ApiResponse(data=results)

    classify_router = create_api_router("/classify", tags=["extraction"])

    @classify_router.post(
        "",
        response_model=ApiResponse[ClassifyResponse],
        summary="Classify text into a category",
    )
    async def classify(body: ClassifyRequest) -> ApiResponse[ClassifyResponse]:
        result = await service.classify(
            body.text,
            body.categories,
            model=body.model,
        )
        return ApiResponse(data=ClassifyResponse(**result))

    # Include classify under the main router so both are returned together
    router.include_router(classify_router)

    return router
