#!/usr/bin/env python
from __future__ import annotations

import json
import os
import pathlib
import urllib.error
import urllib.request
from typing import Any, Literal

from mcp.server.fastmcp import FastMCP


BASE_URL = (
    os.getenv("SDEEKA_BASE_URL")
    or os.getenv("SLEGALTOOLS_BASE_URL")
    or "https://api.sdeeka.com"
).strip().rstrip("/")
TIMEOUT_SECONDS = float(
    os.getenv("SDEEKA_TIMEOUT_SECONDS")
    or os.getenv("SLEGALTOOLS_TIMEOUT_SECONDS")
    or "45"
)
BRIDGE_VERSION = "4.3"


def _load_or_sync_api_key() -> str:
    env_key = (os.getenv("SDEEKA_API_KEY") or os.getenv("SLEGALTOOLS_API_KEY") or "").strip()
    sdeeka_key_file = pathlib.Path.home() / ".sdeeka" / "api_key"
    legacy_key_file = pathlib.Path.home() / ".slegaltools" / "api_key"
    if env_key:
        for key_file in (sdeeka_key_file, legacy_key_file):
            try:
                key_file.parent.mkdir(parents=True, exist_ok=True)
                if not key_file.exists() or key_file.read_text(encoding="utf-8").strip() != env_key:
                    key_file.write_text(env_key + "\n", encoding="utf-8")
                    try:
                        os.chmod(key_file, 0o600)
                    except OSError:
                        pass
            except Exception:
                pass
        return env_key
    for key_file in (sdeeka_key_file, legacy_key_file):
        try:
            if key_file.exists():
                stored = key_file.read_text(encoding="utf-8").strip()
                if stored:
                    return stored
        except Exception:
            pass
    return ""


API_KEY = _load_or_sync_api_key()

mcp = FastMCP("SDeeka Legal Search V4", instructions=(
    "Search fast first, top_k=10 by default, at most 30. Use response_detail=compact to save context. "
    "Inspect candidate excerpts, then fetch only selected cases; never download all candidates automatically. "
    "If fast search is partial or evidence is pending, retry mode=deep at most once. "
    "If deep is still partial, report the limitation and inspect selected cases; do not repeat unchanged searches. "
    "Missing issues mean not found in retrieved evidence, not a definitive negative holding. "
    "Compare both lines of authority when appropriate; scores are relevance, not correctness percentages. "
    "Read selected cases by case_id with include_long_text=true; follow next_offset until null before full analysis. "
    "STRICT COURT SEPARATION: For normal Supreme Court (ศาลฎีกา) or civil/criminal law searches, use ONLY Deka tools (*_deka_*, search_by_law) and DO NOT loop into or call Administrative Court tools (*_admin_*). "
    "Call Administrative Court tools (*_admin_*) ONLY when the user explicitly requests Administrative Court (ศาลปกครอง / คดีปกครอง) or when the dispute is clearly an administrative law matter (e.g. administrative order revocation, civil servant discipline, administrative contract/government procurement, or state official administrative tort)."
))


def _bounded_int(value: Any, default: int, minimum: int, maximum: int) -> int:
    try:
        parsed = int(value)
    except (TypeError, ValueError):
        parsed = default
    return max(minimum, min(maximum, parsed))


def _compact(value: Any) -> Any:
    if value is None or value == "":
        return None
    if isinstance(value, list):
        return [item for item in value if item not in (None, "")]
    return value


def _post(path: str, body: dict[str, Any]) -> dict[str, Any]:
    if not API_KEY:
        return {
            "ok": False,
            "error": "SDEEKA_API_KEY is missing",
            "next_step": "Create an API key at https://sdeeka.com/account/api-keys and set SDEEKA_API_KEY (or SLEGALTOOLS_API_KEY) as an environment variable.",
        }
    clean_body = {key: value for key, value in body.items() if _compact(value) is not None}
    data = json.dumps(clean_body, ensure_ascii=False).encode("utf-8")
    request = urllib.request.Request(
        BASE_URL + path,
        data=data,
        method="POST",
        headers={
            "Authorization": "Bearer " + API_KEY,
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "sdeeka-legal-mcp-bridge/" + BRIDGE_VERSION,
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
            payload = response.read().decode("utf-8", errors="replace")
            return json.loads(payload)
    except urllib.error.HTTPError as exc:
        payload = exc.read().decode("utf-8", errors="replace")
        try:
            details = json.loads(payload)
        except json.JSONDecodeError:
            details = {"body": payload[:500]}
        return {"ok": False, "status": exc.code, "error": "SDeeka MCP API returned an error", "details": details}
    except Exception as exc:
        return {"ok": False, "error": type(exc).__name__, "details": str(exc)}


def _get(path: str) -> dict[str, Any]:
    if not API_KEY:
        return {
            "ok": False,
            "error": "SDEEKA_API_KEY is missing",
            "next_step": "Create an API key at https://sdeeka.com/account/api-keys and set SDEEKA_API_KEY (or SLEGALTOOLS_API_KEY) as an environment variable.",
        }
    request = urllib.request.Request(
        BASE_URL + path,
        method="GET",
        headers={
            "Authorization": "Bearer " + API_KEY,
            "Accept": "application/json",
            "User-Agent": "sdeeka-legal-mcp-bridge/" + BRIDGE_VERSION,
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
            payload = response.read().decode("utf-8", errors="replace")
            return json.loads(payload)
    except urllib.error.HTTPError as exc:
        payload = exc.read().decode("utf-8", errors="replace")
        try:
            details = json.loads(payload)
        except json.JSONDecodeError:
            details = {"body": payload[:500]}
        return {"ok": False, "status": exc.code, "error": "SDeeka MCP API returned an error", "details": details}
    except Exception as exc:
        return {"ok": False, "error": type(exc).__name__, "details": str(exc)}



@mcp.tool()
def plan_deka_search(question: str, top_k: int = 5) -> dict[str, Any]:
    """Plan the best Deka search strategy for a Thai legal question."""
    return _post("/api/tool/plan_deka_search", {"question": question, "top_k": _bounded_int(top_k, 5, 1, 20)})


@mcp.tool(structured_output=False)
def ai_deka_search(question: str, top_k: int = 10, mode: Literal["fast", "deep"] = "fast", response_detail: Literal["compact", "evidence"] = "compact") -> dict[str, Any]:
    """Return concise candidates (max 30). Deep changes retrieval; evidence requests longer excerpts. Read selected cases only."""
    return _post("/api/search/ai", {"question": question, "top_k": _bounded_int(top_k, 10, 1, 30), "mode": mode, "response_detail": response_detail})


@mcp.tool(structured_output=False)
def search_deka_text(
    query: str,
    top_k: int = 10,
    law_code: str | None = None,
    sections: list[str] | str | None = None,
    year_from: int | None = None,
    year_to: int | None = None,
    document_type: str | None = None,
    mode: Literal["fast", "deep"] = "fast",
    response_detail: Literal["compact", "evidence"] = "compact",
) -> dict[str, Any]:
    """Search multiple cases by issue. Use deep for incomplete evidence, then read selected cases in full."""
    return _post(
        "/api/search/text",
        {
            "query": query,
            "top_k": _bounded_int(top_k, 10, 1, 30),
            "law_code": law_code,
            "sections": sections,
            "year_from": year_from,
            "year_to": year_to,
            "document_type": document_type,
            "mode": mode,
            "response_detail": response_detail,
        },
    )


@mcp.tool(structured_output=False)
def search_by_law(
    law_code: str,
    sections: list[str] | str | None = None,
    provision_type: str | None = None,
    top_k: int = 10,
    document_type: str | None = None,
    section_match: Literal["any", "all"] = "any",
    mode: Literal["fast", "deep"] = "fast",
    response_detail: Literal["compact", "evidence"] = "compact",
) -> dict[str, Any]:
    """Search Deka decisions by Thai law code and section numbers."""
    return _post(
        "/api/search/law",
        {
            "law_code": law_code,
            "sections": sections,
            "provision_type": provision_type,
            "top_k": _bounded_int(top_k, 10, 1, 30),
            "document_type": document_type,
            "section_match": section_match,
            "mode": mode,
            "response_detail": response_detail,
        },
    )


@mcp.tool(structured_output=False)
def get_deka_case(
    deka_no: str | None = None,
    include_law_refs: bool = True,
    include_long_text: bool = False,
    max_long_text_chars: int = 30000,
    case_id: int | None = None,
    document_type: str | None = None,
    long_text_offset: int = 0,
) -> dict[str, Any]:
    """Read a selected case by case_id or number/type. Follow next_offset until null to retrieve all long_text."""
    return _post(
        "/api/tool/get_deka_case",
        {
            "deka_no": deka_no,
            "case_id": case_id,
            "document_type": document_type,
            "long_text_offset": long_text_offset,
            "include_law_refs": include_law_refs,
            "include_long_text": include_long_text,
            "max_long_text_chars": _bounded_int(max_long_text_chars, 30000, 500, 30000),
        },
    )


@mcp.tool(structured_output=False)
def make_citation_pack(
    deka_nos: list[str] | None = None,
    case_ids: list[int] | None = None,
    issue: str | None = None,
    facts: str | None = None,
    include_long_text: bool = False,
    max_long_text_chars_per_case: int = 20000,
    top_k_if_search_needed: int = 5,
) -> dict[str, Any]:
    """Build a compact citation pack for one or more Deka decisions."""
    return _post(
        "/api/tool/make_citation_pack",
        {
            "deka_nos": deka_nos,
            "case_ids": case_ids,
            "issue": issue,
            "facts": facts,
            "include_long_text": include_long_text,
            "max_long_text_chars_per_case": _bounded_int(max_long_text_chars_per_case, 20000, 500, 30000),
            "top_k_if_search_needed": _bounded_int(top_k_if_search_needed, 5, 1, 20),
        },
    )


@mcp.tool()
def law_v2_stats() -> dict[str, Any]:
    """Return OCS statute corpus and Law Search V2 index statistics."""
    return _post("/api/tool/law_v2_stats", {})


@mcp.tool()
def law_search_guide_v2() -> dict[str, Any]:
    """Return usage rules for OCS statute search tools."""
    return _post("/api/tool/law_search_guide_v2", {})


@mcp.tool()
def search_laws_v2(
    query: str | None = None,
    topic_code: str | None = None,
    law_type_code: str | None = None,
    fetch_status: str | None = "ok",
    has_text: bool | None = None,
    law_scope: str | None = None,
    lifecycle_status: str | None = "current_or_future",
    top_k: int = 10,
) -> dict[str, Any]:
    """Search OCS law catalog by title, alias, law code, topic, type, scope, lifecycle, and source status."""
    return _post(
        "/api/tool/search_laws_v2",
        {
            "query": query,
            "topic_code": topic_code,
            "law_type_code": law_type_code,
            "fetch_status": fetch_status,
            "has_text": has_text,
            "law_scope": law_scope,
            "lifecycle_status": lifecycle_status,
            "top_k": _bounded_int(top_k, 10, 1, 20),
        },
    )


@mcp.tool()
def search_law_history_v2(
    query: str | None = None,
    law_code: str | None = None,
    law_scope: str | None = None,
    lifecycle_status: str | None = "all",
    top_k: int = 10,
) -> dict[str, Any]:
    """Search OCS law lifecycle/history metadata, including cancelled and amendment listing rows."""
    return _post(
        "/api/tool/search_law_history_v2",
        {
            "query": query,
            "law_code": law_code,
            "law_scope": law_scope,
            "lifecycle_status": lifecycle_status,
            "top_k": _bounded_int(top_k, 10, 1, 20),
        },
    )


@mcp.tool()
def search_law_sections_v2(
    query: str,
    law_code: str | None = None,
    doc_key: str | None = None,
    topic_code: str | None = None,
    section_no: str | int | None = None,
    law_scope: str | None = None,
    lifecycle_status: str | None = "current_or_future",
    top_k: int = 10,
    text_chars: int = 800,
) -> dict[str, Any]:
    """Search Thai statutory text from the OCS corpus. Returns snippets, not full sections."""
    return _post(
        "/api/tool/search_law_sections_v2",
        {
            "query": query,
            "law_code": law_code,
            "doc_key": doc_key,
            "topic_code": topic_code,
            "section_no": section_no,
            "law_scope": law_scope,
            "lifecycle_status": lifecycle_status,
            "top_k": _bounded_int(top_k, 10, 1, 20),
            "text_chars": _bounded_int(text_chars, 800, 120, 5000),
        },
    )


@mcp.tool(structured_output=False)
def get_law_section_v2(
    section_key: str | None = None,
    doc_key: str | None = None,
    law_code: str | None = None,
    section_no: str | int | None = None,
    include_html: bool = False,
    max_text_chars: int = 30000,
) -> dict[str, Any]:
    """Get full text for one OCS law section by section_key, or by law_code/doc_key plus section_no."""
    return _post(
        "/api/tool/get_law_section_v2",
        {
            "section_key": section_key,
            "doc_key": doc_key,
            "law_code": law_code,
            "section_no": section_no,
            "include_html": include_html,
            "max_text_chars": _bounded_int(max_text_chars, 30000, 500, 30000),
        },
    )


@mcp.tool()
def list_template_categories() -> dict[str, Any]:
    """List available Thai legal pleading template categories and counts (Free)."""
    return _post("/api/tool/list_template_categories", {})


@mcp.tool()
def search_templates(
    query: str | None = None,
    category: str | None = None,
    limit: int = 10,
) -> dict[str, Any]:
    """Search 242 Thai legal pleading templates by keyword or category (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/search_templates",
        {
            "query": query,
            "category": category,
            "limit": _bounded_int(limit, 10, 1, 20),
        },
    )


@mcp.tool()
def get_template(template_id: str) -> dict[str, Any]:
    """Retrieve the full Thai legal pleading template body and placeholders by template_id (Requires templates_pro Add-on)."""
    return _post("/api/tool/get_template", {"template_id": template_id})


@mcp.tool()
def get_template_field_map() -> dict[str, Any]:
    """Retrieve the standard placeholder field map for Thai legal templates (Requires templates_pro Add-on)."""
    return _post("/api/tool/get_template_field_map", {})


@mcp.tool()
def get_template_drafting_guide() -> dict[str, Any]:
    """Retrieve the Thai legal pleading template drafting guide (Requires templates_pro Add-on)."""
    return _post("/api/tool/get_template_drafting_guide", {})


@mcp.tool()
def get_pleading_patterns(
    category: str | None = None,
    pattern: str | None = None,
    block_id: str | None = None,
    include_blocks: bool = False,
    include_checklist: bool = True,
) -> dict[str, Any]:
    """List Thai pleading complaint titles and scenarios (3 main case types: Loan, Sale, Tort • 14 scenarios). Free tier returns complaint titles only; Templates Pro Add-on unlocks locked block definitions and checklists."""
    return _post(
        "/api/tool/get_pleading_patterns",
        {
            "category": category,
            "pattern": pattern,
            "block_id": block_id,
            "include_blocks": include_blocks,
            "include_checklist": include_checklist,
        },
    )


@mcp.tool()
def render_pleading_packet(
    packet: dict[str, Any],
    mode: str = "full",
) -> dict[str, Any]:
    """Validate and render locked Thai pleading paragraphs from an evidence-backed packet (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/render_pleading_packet",
        {
            "packet": packet,
            "mode": mode,
        },
    )


@mcp.tool()
def check_pleading_draft(
    packet: dict[str, Any],
    draft_text: str,
    mode: str = "full",
) -> dict[str, Any]:
    """Verify that a Thai complaint draft preserves all locked pleading clauses verbatim (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/check_pleading_draft",
        {
            "packet": packet,
            "draft_text": draft_text,
            "mode": mode,
        },
    )


@mcp.tool()
def list_petition_patterns(
    category: str | None = None,
    query: str | None = None,
    limit: int = 80,
    include_blocks: bool = False,
) -> dict[str, Any]:
    """List Thai court petition patterns (คำร้อง/คำแถลง/คำขอ) across 78 standard templates. Free tier returns petition titles only; Templates Pro Add-on unlocks locked 3-part template metadata."""
    return _post(
        "/api/tool/list_petition_patterns",
        {
            "category": category,
            "query": query,
            "limit": _bounded_int(limit, 80, 1, 100),
            "include_blocks": include_blocks,
        },
    )


@mcp.tool()
def inspect_petition_pattern(
    pattern_id: str,
    variant: str = "future_date",
) -> dict[str, Any]:
    """Inspect a locked Thai court petition pattern, required slots, and 3-part template structure (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/inspect_petition_pattern",
        {
            "pattern_id": pattern_id,
            "variant": variant,
        },
    )


@mcp.tool()
def scan_petition_packet(
    packet: dict[str, Any],
    variant: str | None = None,
) -> dict[str, Any]:
    """Check which required slots and case facts are still missing in a Thai court petition packet (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/scan_petition_packet",
        {
            "packet": packet,
            "variant": variant,
        },
    )


@mcp.tool()
def render_petition_packet(
    packet: dict[str, Any],
    variant: str | None = None,
) -> dict[str, Any]:
    """Validate and render a locked 3-part Thai court petition from an evidence-backed packet (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/render_petition_packet",
        {
            "packet": packet,
            "variant": variant,
        },
    )


@mcp.tool()
def check_petition_draft(
    packet: dict[str, Any],
    draft_text: str,
    variant: str | None = None,
) -> dict[str, Any]:
    """Verify that a Thai court petition draft preserves all locked 3-part petition clauses verbatim (Requires templates_pro Add-on)."""
    return _post(
        "/api/tool/check_petition_draft",
        {
            "packet": packet,
            "draft_text": draft_text,
            "variant": variant,
        },
    )


def _account_and_updates() -> dict[str, Any]:
    info = _get("/api/account/entitlements")
    if isinstance(info, dict):
        info["local_bridge_version"] = BRIDGE_VERSION
    return info


@mcp.tool()
def get_sdeeka_account_and_updates() -> dict[str, Any]:
    """Check current SDeeka account entitlements (Free Forever Deka/Law V2 vs AdminCourt Add-on & Templates Pro Pleading/Petition Add-on) and local MCP bridge version."""
    return _account_and_updates()


@mcp.tool()
def get_slegaltools_account_and_updates() -> dict[str, Any]:
    """Check current SDeeka / SLegalTools account entitlements (Free Forever Deka/Law V2 vs AdminCourt Add-on & Templates Pro Pleading/Petition Add-on) and local MCP bridge version."""
    return _account_and_updates()


@mcp.tool()
def list_admin_facets() -> dict[str, Any]:
    """List Thai Administrative Court (ศาลปกครอง) corpus statistics, 37 official categories, 25 procedural tags, and vector store status. Use ONLY for Administrative Court (ศาลปกครอง / คดีปกครอง) tasks."""
    return _post("/api/tool/list_admin_facets", {})


@mcp.tool(structured_output=False)
def search_admin_cases(
    query: str | None = None,
    category: str | None = None,
    procedural_tag: str | None = None,
    court_level: str | None = None,
    doc_type: str | None = None,
    decided_on: str | None = None,
    plaintiff_result: str | None = None,
    agency: str | None = None,
    year_from: int | None = None,
    year_to: int | None = None,
    use_vector: bool = True,
    top_k: int = 10,
) -> dict[str, Any]:
    """Hybrid search over Thai Administrative Court (ศาลปกครอง) judgments and orders (Requires admincourt_pro Add-on). IMPORTANT: Call ONLY when the user explicitly asks for ศาลปกครอง/คดีปกครอง or when the issue is clearly an administrative law/administrative court dispute. DO NOT call as a fallback for normal Supreme Court (ศาลฎีกา) civil/criminal searches."""
    return _post(
        "/api/tool/search_admin_cases",
        {
            "query": query,
            "category": category,
            "procedural_tag": procedural_tag,
            "court_level": court_level,
            "doc_type": doc_type,
            "decided_on": decided_on,
            "plaintiff_result": plaintiff_result,
            "agency": agency,
            "year_from": year_from,
            "year_to": year_to,
            "use_vector": use_vector,
            "top_k": _bounded_int(top_k, 10, 1, 30),
        },
    )


@mcp.tool(structured_output=False)
def search_admin_by_law(
    law_code: str,
    section: str | None = None,
    query: str | None = None,
    category: str | None = None,
    top_k: int = 10,
) -> dict[str, Any]:
    """Search Thai Administrative Court (ศาลปกครอง) decisions by statute name/code (`law_code`) and section number (`section`) (Requires admincourt_pro Add-on). Call ONLY for Administrative Court / administrative law disputes; for Supreme Court (ศาลฎีกา), use `search_by_law` instead."""
    return _post(
        "/api/tool/search_admin_by_law",
        {
            "law_code": law_code,
            "section": section,
            "query": query,
            "category": category,
            "top_k": _bounded_int(top_k, 10, 1, 30),
        },
    )


@mcp.tool(structured_output=False)
def get_admin_case(
    case_id_or_red_no: str,
    include_full_text: bool = False,
    max_text_chars: int = 30000,
) -> dict[str, Any]:
    """Get a Thai Administrative Court (ศาลปกครอง) case by `case_id` or `red_no` (e.g., 'อ. 123/2566', 'อผ. 5/2569', 'คำสั่งที่ 13/2569') (Requires admincourt_pro Add-on). For Supreme Court (ศาลฎีกา) cases, use `get_deka_case`."""
    return _post(
        "/api/tool/get_admin_case",
        {
            "case_id_or_red_no": case_id_or_red_no,
            "include_full_text": include_full_text,
            "max_text_chars": _bounded_int(max_text_chars, 30000, 500, 30000),
        },
    )


@mcp.tool(structured_output=False)
def admin_citation_pack(
    case_ids_or_red_nos: list[str],
    query_focus: str | None = None,
    max_chunks_per_case: int = 3,
) -> dict[str, Any]:
    """Build a citation pack for 1-10 Thai Administrative Court (ศาลปกครอง) cases with legal principles, disposition details, law refs, and reasoning chunks (Requires admincourt_pro Add-on)."""
    return _post(
        "/api/tool/admin_citation_pack",
        {
            "case_ids_or_red_nos": case_ids_or_red_nos[:10] if case_ids_or_red_nos else [],
            "query_focus": query_focus,
            "max_chunks_per_case": _bounded_int(max_chunks_per_case, 3, 1, 10),
        },
    )


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