"""
falcao_mcp: MCP server for the Sistema Falcão de Busca de Jurisprudência
(Justiça do Trabalho: TST + all 24 TRTs).

The Falcão system (https://jurisprudencia.jt.jus.br/) is a JavaScript
single-page app maintained by the CSJT (Resolução CSJT 401/2024). It talks
to an unauthenticated backend endpoint that was not designed as a public
API and has no published contract or SLA. This server wraps it as best
it can; endpoints may change or be restricted without notice.

Confirmed empirically (2026-08-25):
- Endpoint: GET {BASE_URL}/pesquisa
- "sessionId" is not a real server-side session; any string in the shape
  "_" + 7 alphanumeric chars is accepted.
- Anonymous requests are restricted to page sizes 5 or 10 (any other
  value returns HTTP 403 with a "tamanho de página" message).
- No rate limiting or CAPTCHA observed at moderate volumes (~100
  sequential/parallel requests in a few seconds), but this was not
  exhaustively tested and should not be relied upon for bulk scraping.
"""

import random
import string
from enum import Enum
from typing import Any, Dict, List, Optional

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

# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

BASE_URL = "https://jurisprudencia.jt.jus.br/jurisprudencia-nacional-backend/api/no-auth"
SEARCH_URL = f"{BASE_URL}/pesquisa"
FILTROS_URL = f"{BASE_URL}/pesquisa/filtros"
AUTOCOMPLETE_URL = f"{BASE_URL}/autocompletar"

REQUEST_TIMEOUT_SECONDS = 20.0

# The API appears to reject requests that don't look like they came from
# the Falcão web app itself (no custom User-Agent, no Referer). These
# headers mirror what the browser sends; without them, real-world testing
# showed the API returns 403 even with valid params.
REQUEST_HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
    ),
    "Referer": "https://jurisprudencia.jt.jus.br/jurisprudencia-nacional/pesquisa",
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "pt-BR,pt;q=0.9",
}

# Anonymous access only accepts these two page sizes; anything else -> 403.
VALID_PAGE_SIZES = (5, 10)

VALID_TRIBUNAIS = {
    "TST",
    *{f"TRT{i}" for i in range(1, 25)},
}

# ---------------------------------------------------------------------------
# Enums / Models
# ---------------------------------------------------------------------------


class Colecao(str, Enum):
    """Collections available in Falcão. Values match the API's own codes."""

    ACORDAOS = "acordaos"
    SENTENCAS = "sentencas"
    DECISOES_MONOCRATICAS = "decisoesmonocraticas"
    PRECEDENTES = "precedentes"
    RECURSO_REVISTA = "recursorevista"


class SearchJurisprudenceInput(BaseModel):
    """Input for searching Brazilian labor court case law via Falcão."""

    model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")

    texto: str = Field(
        ...,
        description=(
            "Free-text search query in Portuguese, e.g. 'horas extras "
            "cargo de confianca' or 'dano moral assedio'."
        ),
        min_length=1,
        max_length=500,
    )
    tribunais: Optional[List[str]] = Field(
        default=None,
        description=(
            "Restrict the search to specific courts. Valid codes: 'TST' "
            "(Tribunal Superior do Trabalho) and 'TRT1' through 'TRT24' "
            "(Regional Labor Courts; TRT2 = São Paulo capital, "
            "TRT15 = Campinas/interior de SP). Omit or leave empty to "
            "search all courts."
        ),
        max_length=25,
    )
    colecao: Colecao = Field(
        default=Colecao.ACORDAOS,
        description=(
            "Which collection to search: 'acordaos' (appellate panel "
            "decisions, most common choice), 'sentencas' (first-instance "
            "rulings), 'decisoesmonocraticas' (single-judge decisions), "
            "'precedentes' (binding precedents / súmulas / IRDRs), or "
            "'recursorevista' (recurso de revista admissibility "
            "decisions)."
        ),
    )
    apenas_ementa: bool = Field(
        default=False,
        description=(
            "If true, only match the search text against the ementa "
            "(headnote) instead of the full decision text. Narrower and "
            "faster to scan, but can miss relevant decisions whose "
            "ementa does not use the searched terms."
        ),
    )
    page: int = Field(
        default=0,
        description="Zero-indexed page number.",
        ge=0,
    )
    page_size: int = Field(
        default=10,
        description=(
            "Results per page. Anonymous access only allows 5 or 10; "
            "any other value is rejected by the source API."
        ),
    )

    def validated_page_size(self) -> int:
        if self.page_size not in VALID_PAGE_SIZES:
            raise ValueError(
                f"page_size must be one of {VALID_PAGE_SIZES} for "
                f"anonymous access (got {self.page_size})."
            )
        return self.page_size

    def validated_tribunais(self) -> List[str]:
        if not self.tribunais:
            return []
        cleaned = [t.strip().upper() for t in self.tribunais]
        invalid = [t for t in cleaned if t not in VALID_TRIBUNAIS]
        if invalid:
            raise ValueError(
                f"Invalid tribunal code(s): {invalid}. Valid codes are "
                f"'TST' and 'TRT1'-'TRT24'."
            )
        return cleaned


class AutocompleteInput(BaseModel):
    """Input for fetching search-term suggestions from Falcão."""

    model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")

    texto_parcial: str = Field(
        ...,
        description="Partial search text to get autocomplete suggestions for.",
        min_length=1,
        max_length=200,
    )


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _fake_session_id() -> str:
    """Falcão's 'sessionId' is not a validated server session: any string
    of the form '_' + 7 alphanumeric characters is accepted. Generated
    fresh per request so calls are independent of one another."""
    chars = string.ascii_lowercase + string.digits
    return "_" + "".join(random.choices(chars, k=7))


async def _get_json(client: httpx.AsyncClient, url: str, params: Dict[str, Any]) -> Dict[str, Any]:
    response = await client.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
    if response.status_code != 200:
        try:
            body = response.json()
            detail = body.get("userMessage") or body.get("developerMessage") or response.text
        except Exception:
            detail = response.text
        raise httpx.HTTPStatusError(
            f"Falcão API returned {response.status_code}: {detail}",
            request=response.request,
            response=response,
        )
    return response.json()


def _format_document(doc: Dict[str, Any]) -> Dict[str, Any]:
    """Trim a raw Falcão document down to the fields that matter for
    legal research, dropping highlight/HTML-noise fields."""
    return {
        "numero_processo": doc.get("numeroProcesso"),
        "tribunal": doc.get("tribunal"),
        "orgao_julgador": doc.get("turma") or doc.get("gabinete"),
        "classe_processual": doc.get("classeProcesso") or doc.get("siglaClasseProcesso"),
        "relator": doc.get("relator"),
        "data_julgamento": doc.get("dataJulgamento"),
        "data_juntada": doc.get("dataJuntada"),
        "ementa": doc.get("ementa"),
        "inteiro_teor_html": doc.get("textoAcordao"),
        "referencia_legislativa": doc.get("referenciaLegislativa"),
        "score": doc.get("score"),
    }


def _handle_api_error(e: Exception) -> str:
    """Consistent, actionable error formatting across all tools."""
    if isinstance(e, httpx.HTTPStatusError):
        status = e.response.status_code
        if status == 403:
            return (
                f"Error: request rejected by Falcão (403). {e}. "
                "If this mentions page size, only 5 or 10 are accepted "
                "for anonymous access."
            )
        if status == 404:
            return "Error: endpoint not found (404). The Falcão API may have changed."
        if status == 429:
            return "Error: rate limited by Falcão (429). Wait before retrying."
        return f"Error: Falcão API request failed with status {status}: {e}"
    if isinstance(e, httpx.TimeoutException):
        return "Error: request to Falcão timed out. Please try again."
    if isinstance(e, ValueError):
        return f"Error: {e}"
    return f"Error: unexpected error ({type(e).__name__}): {e}"


# ---------------------------------------------------------------------------
# Server
# ---------------------------------------------------------------------------

mcp = FastMCP("falcao_mcp")


@mcp.tool(
    name="falcao_search_jurisprudence",
    annotations={
        "title": "Search Brazilian labor court case law (TST + TRTs)",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": True,
    },
)
async def falcao_search_jurisprudence(params: SearchJurisprudenceInput) -> Dict[str, Any]:
    """Search Brazilian Justiça do Trabalho case law (TST and all 24 TRTs)
    via the Sistema Falcão, returning full ementa and inteiro teor text.

    Use this to find labor-law precedents, appellate decisions, first
    instance rulings, or binding precedents on a topic, optionally
    restricted to specific courts (e.g. only TRT2 and TRT15).

    Args:
        params (SearchJurisprudenceInput): Validated input containing:
            - texto (str): free-text search query
            - tribunais (Optional[List[str]]): court codes to filter by
            - colecao (Colecao): which collection to search
            - apenas_ementa (bool): restrict matching to the ementa only
            - page (int): zero-indexed page number
            - page_size (int): results per page (5 or 10)

    Returns:
        dict: {
            "quantidade_total": int,       # total matches (capped by the source API)
            "pagina": int,
            "tamanho_pagina": int,
            "temas_relacionados": [str],   # top related topics, if any
            "documentos": [
                {
                    "numero_processo": str,
                    "tribunal": str,             # e.g. "TRT2"
                    "orgao_julgador": str,
                    "classe_processual": str,
                    "relator": str,
                    "data_julgamento": str,      # "DD/MM/YYYY"
                    "data_juntada": str,
                    "ementa": str,
                    "inteiro_teor_html": str,     # full decision text, HTML-formatted
                    "referencia_legislativa": str,
                    "score": float,
                },
                ...
            ]
        }
        On failure, returns {"error": "<actionable message>"} instead.
    """
    try:
        page_size = params.validated_page_size()
        tribunais = params.validated_tribunais()
    except ValueError as e:
        return {"error": _handle_api_error(e)}

    query_params = {
        "sessionId": _fake_session_id(),
        "latitude": 0,
        "longitude": 0,
        "texto": params.texto,
        "verTodosPrecedentes": "false",
        "tribunais": ",".join(tribunais),
        "pesquisaSomenteNasEmentas": str(params.apenas_ementa).lower(),
        "colecao": params.colecao.value,
        "page": params.page,
        "size": page_size,
    }

    try:
        async with httpx.AsyncClient(headers=REQUEST_HEADERS) as client:
            data = await _get_json(client, SEARCH_URL, query_params)
    except Exception as e:
        return {"error": _handle_api_error(e)}

    documentos = [_format_document(d) for d in data.get("documentos", [])]
    temas = [t.get("nome") if isinstance(t, dict) else t for t in (data.get("temasTopFive") or [])]

    return {
        "quantidade_total": data.get("quantidadeTotal"),
        "pagina": params.page,
        "tamanho_pagina": page_size,
        "temas_relacionados": temas,
        "documentos": documentos,
    }


@mcp.tool(
    name="falcao_autocomplete",
    annotations={
        "title": "Get search-term suggestions from Falcão",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": True,
    },
)
async def falcao_autocomplete(params: AutocompleteInput) -> Dict[str, Any]:
    """Get autocomplete suggestions for a partial search term, as used by
    Falcão's own search box. Useful for discovering the exact legal
    terminology or súmula/tema names before running a full search.

    Args:
        params (AutocompleteInput): Validated input containing:
            - texto_parcial (str): partial search text

    Returns:
        dict: {"sugestoes": [str, ...]} on success, or
              {"error": "<actionable message>"} on failure.
    """
    try:
        async with httpx.AsyncClient(headers=REQUEST_HEADERS) as client:
            data = await _get_json(
                client, AUTOCOMPLETE_URL, {"texto": params.texto_parcial}
            )
    except Exception as e:
        return {"error": _handle_api_error(e)}

    # The raw response shape has varied between plain lists and objects;
    # normalize defensively.
    if isinstance(data, list):
        sugestoes = data
    elif isinstance(data, dict):
        sugestoes = data.get("sugestoes") or data.get("items") or list(data.values())
    else:
        sugestoes = []

    return {"sugestoes": sugestoes}


@mcp.tool(
    name="falcao_list_tribunais",
    annotations={
        "title": "List valid court codes accepted by Falcão",
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
        "openWorldHint": False,
    },
)
async def falcao_list_tribunais() -> Dict[str, Any]:
    """List the court codes accepted by the 'tribunais' parameter of
    falcao_search_jurisprudence, with their document counts as last
    observed. Call this if unsure which code corresponds to which
    regional labor court.

    Returns:
        dict: {"tribunais": [{"codigo": str, "nome": str, "quantidade_acordaos": int}, ...]}
              or {"error": "<actionable message>"} on failure.
    """
    try:
        async with httpx.AsyncClient(headers=REQUEST_HEADERS) as client:
            data = await _get_json(
                client,
                FILTROS_URL,
                {
                    "sessionId": _fake_session_id(),
                    "latitude": 0,
                    "longitude": 0,
                    "texto": "",
                    "verTodosPrecedentes": "false",
                    "tribunais": "",
                    "pesquisaSomenteNasEmentas": "false",
                    "colecao": "acordaos",
                },
            )
    except Exception as e:
        return {"error": _handle_api_error(e)}

    filtros = data.get("filtrosDisponiveis", [])
    tribunal_filtro = next(
        (f for f in filtros if f.get("nomeDoFiltro") == "tribunal"), None
    )
    if not tribunal_filtro:
        return {"tribunais": []}

    tribunais = [
        {
            "codigo": v.get("valor"),
            "nome": v.get("valorBalao") or v.get("valorWeb"),
            "quantidade_acordaos": v.get("quantidade"),
        }
        for v in tribunal_filtro.get("valoresFiltro", [])
    ]
    return {"tribunais": tribunais}


if __name__ == "__main__":
    mcp.run()