"""CSJN MCP Server — Argentine Supreme Court sumarios search."""

from __future__ import annotations

import json

from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field

from .client import CSJNError, autocomplete_voces, get_analisis, search

mcp = FastMCP(
    "csjn",
    instructions=(
        "Search sumarios from CSJN (Corte Suprema de Justicia de la Nación) — "
        "the Argentine Supreme Court. Access case summaries, legal topics (voces), "
        "detailed analysis, and metadata from 1994 to present."
    ),
)


# --- Input models ---


class SearchInput(BaseModel):
    """Input for csjn_search."""

    query: str = Field(..., description="Search terms (e.g. 'defensa consumidor', 'prescripción')", min_length=1)
    autos: str = Field("", description="Filter by case name/caption")
    fecha_desde: str = Field("", description="Start date filter (DD/MM/YYYY)")
    fecha_hasta: str = Field("", description="End date filter (DD/MM/YYYY)")
    limit: int = Field(10, description="Maximum results (default 10)", ge=1, le=50)


class GetAnalisisInput(BaseModel):
    """Input for csjn_get_analisis."""

    id_sumario: int = Field(..., description="Sumario ID from search results (e.g. 175275)")


class AutocompleteVocesInput(BaseModel):
    """Input for csjn_autocomplete_voces."""

    term: str = Field(..., description="Partial topic name (e.g. 'prescripcion', 'consumidor')", min_length=1)


# --- Tools ---


_ANNOTATIONS = {
    "readOnlyHint": True,
    "destructiveHint": False,
    "idempotentHint": True,
    "openWorldHint": True,
}


@mcp.tool(annotations=_ANNOTATIONS)
def csjn_search(params: SearchInput) -> str:
    """Search CSJN sumarios by full text, case name, or date range.

    Returns JSON with total count and result list. Each result has: id, voces
    (legal topics), texto (summary), autos (case name), fecha, tomo,
    pagina, expediente, and id_fallo.
    """
    try:
        result = search(
            params.query,
            autos=params.autos,
            fecha_desde=params.fecha_desde,
            fecha_hasta=params.fecha_hasta,
            limit=params.limit,
        )
        return json.dumps(result, ensure_ascii=False, indent=2)
    except CSJNError as e:
        return json.dumps({"error": str(e)})


@mcp.tool(annotations=_ANNOTATIONS)
def csjn_get_analisis(params: GetAnalisisInput) -> str:
    """Get detailed analysis of a CSJN sumario by its numeric ID.

    Returns competencia, tipo de recurso, sentido del pronunciamiento,
    materia, remisión, and fallo destacado (highlighted ruling summary).
    """
    try:
        result = get_analisis(params.id_sumario)
        return json.dumps(result, ensure_ascii=False, indent=2)
    except CSJNError as e:
        return json.dumps({"error": str(e)})


@mcp.tool(annotations=_ANNOTATIONS)
def csjn_autocomplete_voces(params: AutocompleteVocesInput) -> str:
    """Autocomplete legal topics (voces) used in CSJN classification.

    Returns JSON list of matching voces with their IDs.
    """
    try:
        result = autocomplete_voces(params.term)
        return json.dumps(result, ensure_ascii=False, indent=2)
    except CSJNError as e:
        return json.dumps({"error": str(e)})


def main():
    mcp.run()


if __name__ == "__main__":
    main()
