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

from __future__ import annotations

import json

from mcp.server.fastmcp import FastMCP

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."
    ),
)


@mcp.tool()
def csjn_search(
    query: str,
    autos: str = "",
    fecha_desde: str = "",
    fecha_hasta: str = "",
    limit: int = 10,
) -> str:
    """Search CSJN sumarios by full text, case name, or date range.

    Args:
        query: Search terms (e.g., "defensa consumidor", "prescripción").
        autos: Filter by case name/caption.
        fecha_desde: Start date filter (DD/MM/YYYY).
        fecha_hasta: End date filter (DD/MM/YYYY).
        limit: Maximum results to return (default 10).

    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(
            query,
            autos=autos,
            fecha_desde=fecha_desde,
            fecha_hasta=fecha_hasta,
            limit=limit,
        )
        return json.dumps(result, ensure_ascii=False, indent=2)
    except CSJNError as e:
        return json.dumps({"error": str(e)})


@mcp.tool()
def csjn_get_analisis(id_sumario: int) -> 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).

    Args:
        id_sumario: Sumario ID from search results (e.g., 175275).
    """
    try:
        result = get_analisis(id_sumario)
        return json.dumps(result, ensure_ascii=False, indent=2)
    except CSJNError as e:
        return json.dumps({"error": str(e)})


@mcp.tool()
def csjn_autocomplete_voces(term: str) -> str:
    """Autocomplete legal topics (voces) used in CSJN classification.

    Args:
        term: Partial topic name (e.g., "prescripcion", "consumidor").

    Returns:
        JSON list of matching voces with their IDs.
    """
    try:
        result = autocomplete_voces(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()
