"""Brehon Privacy API — MCP Server.

Exposes 10 tools and 3 resources for querying 32+ global privacy laws
via the Brehon Privacy API (https://brehon.dev).
"""

import json

from mcp.server.fastmcp import FastMCP

from brehon_mcp_server.client import get_client

mcp = FastMCP("Brehon Privacy API")


# ── Helpers ──────────────────────────────────────────────────────

def _json(data: object) -> str:
    return json.dumps(data, indent=2, default=str)


def _is_error(result: object) -> bool:
    return isinstance(result, dict) and result.get("error") is True


# ── Tools ────────────────────────────────────────────────────────


@mcp.tool()
async def search_privacy_laws(
    law_type: str | None = None,
    jurisdiction: str | None = None,
    geographic_scope: str | None = None,
    sub_type: str | None = None,
) -> str:
    """Search and filter privacy laws by type, jurisdiction, or geographic scope.

    All parameters are optional. Returns a list of matching privacy law summaries.
    Example law_type values: gdpr, pipeda, ccpa, cpra.
    """
    result = await get_client().search_privacy_laws(
        law_type=law_type,
        jurisdiction=jurisdiction,
        geographic_scope=geographic_scope,
        sub_type=sub_type,
    )
    return _json(result)


@mcp.tool()
async def get_privacy_law_details(law_id: str) -> str:
    """Get full details for a specific privacy law by its ID.

    Example IDs: gdpr-eu, ccpa-ca-us, pipeda-ca, lgpd-br-2018.
    Returns the complete law record including rights, penalties, legal bases,
    key principles, and exemptions — each with a legal_reference citing the
    specific statutory article or section.
    """
    result = await get_client().get_privacy_law_details(law_id)
    return _json(result)


@mcp.tool()
async def get_data_subject_rights(law_id: str) -> str:
    """Get data subject rights granted by a specific privacy law.

    Returns the list of rights (e.g. right to access, right to erasure)
    with descriptions, conditions, and legal_reference (statutory citation).
    """
    result = await get_client().get_data_subject_rights(law_id)
    return _json(result)


@mcp.tool()
async def get_legal_bases(law_id: str) -> str:
    """Get the legal bases for data processing under a specific privacy law.

    Returns lawful grounds for processing personal data (e.g. consent,
    legitimate interest, contractual necessity) with legal_reference
    (statutory citation) for each basis.
    """
    result = await get_client().get_legal_bases(law_id)
    return _json(result)


@mcp.tool()
async def get_penalties(law_id: str) -> str:
    """Get penalty and enforcement information for a specific privacy law.

    Returns fine amounts, enforcement authority details, and penalty tiers,
    each with a legal_reference (statutory citation).
    """
    result = await get_client().get_penalties(law_id)
    return _json(result)


@mcp.tool()
async def get_principles(law_id: str) -> str:
    """Get key principles for a specific privacy law.

    Returns the foundational principles (e.g. purpose limitation, data
    minimisation, accountability) each with a legal_reference (statutory citation).
    """
    result = await get_client().get_principles(law_id)
    return _json(result)


@mcp.tool()
async def get_exemptions(law_id: str) -> str:
    """Get exemptions for a specific privacy law.

    Returns the list of exemptions (e.g. personal/household use, journalism,
    national security) each with a legal_reference (statutory citation).
    """
    result = await get_client().get_exemptions(law_id)
    return _json(result)


@mcp.tool()
async def compare_privacy_laws(law_ids: list[str]) -> str:
    """Compare compliance requirements across multiple privacy laws.

    Provide at least 2 law IDs. Returns a side-by-side comparison of
    key requirements, rights, and penalties.
    """
    if len(law_ids) < 2:
        return _json({"error": True, "detail": "At least 2 law IDs are required for comparison."})
    result = await get_client().compare_privacy_laws(law_ids)
    return _json(result)


@mcp.tool()
async def search_law_content(query: str, fields: list[str] | None = None) -> str:
    """Keyword search across all privacy law content.

    Searches descriptions, rights, penalties, notification requirements, etc.
    Optionally restrict to specific fields (e.g. ['penalties', 'notification_requirements']).
    """
    fields_str = ",".join(fields) if fields else None
    result = await get_client().search_law_content(query, fields=fields_str)
    return _json(result)


@mcp.tool()
async def get_applicable_laws(jurisdictions: list[str]) -> str:
    """Get all privacy laws applicable to the given jurisdictions.

    Provide a list of jurisdiction names (e.g. ['India', 'European Union', 'California']).
    Returns all laws that apply to those regions.
    """
    result = await get_client().get_applicable_laws(jurisdictions)
    return _json(result)


# ── Resources ────────────────────────────────────────────────────


@mcp.resource("privacy-law://summary")
async def laws_summary() -> str:
    """Summary of all 32+ privacy laws in the database."""
    result = await get_client().get_all_laws_summary()
    return _json(result)


@mcp.resource("privacy-law://jurisdictions")
async def jurisdictions() -> str:
    """List of all available jurisdictions."""
    result = await get_client().get_jurisdictions()
    return _json(result)


@mcp.resource("privacy-law://{law_id}")
async def law_details(law_id: str) -> str:
    """Full details for a specific privacy law."""
    result = await get_client().get_privacy_law_details(law_id)
    return _json(result)


# ── Entry point ──────────────────────────────────────────────────


def main() -> None:
    """Run the MCP server (stdio transport)."""
    mcp.run()


if __name__ == "__main__":
    main()
