"""MCP prompt definitions for GA4GH workflows.

Prompts provide pre-built interaction templates for common GA4GH
use cases, helping LLMs structure their interactions with GA4GH APIs.
"""

from __future__ import annotations

from mcp.types import GetPromptResult, PromptMessage, TextContent

PROMPTS = [
    {
        "name": "find_variants",
        "description": "Search for genetic variants across GA4GH Beacon networks.",
        "arguments": [
            {"name": "gene", "description": "Gene name (e.g., BRCA1, TP53)", "required": True},
            {
                "name": "variant_type",
                "description": "Type of variant (SNV, indel, structural)",
                "required": False,
            },
        ],
    },
    {
        "name": "patient_summary",
        "description": "Generate a clinical summary from Phenopacket data.",
        "arguments": [
            {
                "name": "phenopacket_json",
                "description": "JSON Phenopacket document",
                "required": True,
            },
        ],
    },
    {
        "name": "rare_disease_search",
        "description": "Search for rare disease data across federated GA4GH sources.",
        "arguments": [
            {
                "name": "disease",
                "description": "Disease name or ontology ID (e.g., OMIM:100100)",
                "required": True,
            },
            {"name": "phenotypes", "description": "Comma-separated HPO terms", "required": False},
        ],
    },
    {
        "name": "workflow_submit",
        "description": "Submit a bioinformatics workflow to a WES/TES server.",
        "arguments": [
            {"name": "workflow_url", "description": "URL to workflow document", "required": True},
            {"name": "server_url", "description": "WES server base URL", "required": True},
            {
                "name": "workflow_type",
                "description": "Workflow type (CWL, WDL, Nextflow)",
                "required": False,
            },
        ],
    },
    {
        "name": "compliance_report",
        "description": "Generate a GA4GH compliance report for a server.",
        "arguments": [
            {"name": "server_url", "description": "Server base URL to test", "required": True},
            {
                "name": "spec",
                "description": "GA4GH specification to test (beacon, drs, wes, etc.)",
                "required": True,
            },
        ],
    },
]


def list_prompts() -> list[dict]:
    """Return all available prompts."""
    return PROMPTS


def get_prompt(name: str, arguments: dict | None = None) -> GetPromptResult:
    """Get a prompt by name and render with arguments."""
    args = arguments or {}
    renderer = _PROMPT_RENDERERS.get(name)
    if renderer is None:
        return GetPromptResult(
            description=f"Unknown prompt: {name}",
            messages=[
                PromptMessage(
                    role="user",
                    content=TextContent(type="text", text=f"Unknown prompt: {name}"),
                )
            ],
        )
    return renderer(args)


def _find_variants(args: dict) -> GetPromptResult:
    gene = args.get("gene", "BRCA1")
    variant_type = args.get("variant_type", "any")
    return GetPromptResult(
        description=f"Find {variant_type} variants in {gene}",
        messages=[
            PromptMessage(
                role="user",
                content=TextContent(
                    type="text",
                    text=(
                        f"Search for {variant_type} variants in the {gene} gene across "
                        f"GA4GH Beacon networks.\n\n"
                        f"Use the beacon_query tool to query for variants in {gene}. "
                        f"Summarize findings including allele frequencies, clinical "
                        f"significance, and data availability across beacons."
                    ),
                ),
            )
        ],
    )


def _patient_summary(args: dict) -> GetPromptResult:
    phenopacket_json = args.get("phenopacket_json", "{}")
    return GetPromptResult(
        description="Generate clinical summary from Phenopacket",
        messages=[
            PromptMessage(
                role="user",
                content=TextContent(
                    type="text",
                    text=(
                        f"Analyze the following Phenopacket and generate a clinical summary:\n\n"
                        f"```json\n{phenopacket_json}\n```\n\n"
                        f"Include: patient demographics, phenotypic features, diagnoses, "
                        f"genetic findings, and recommended next steps."
                    ),
                ),
            )
        ],
    )


def _rare_disease_search(args: dict) -> GetPromptResult:
    disease = args.get("disease", "")
    phenotypes = args.get("phenotypes", "")
    return GetPromptResult(
        description=f"Search for rare disease: {disease}",
        messages=[
            PromptMessage(
                role="user",
                content=TextContent(
                    type="text",
                    text=(
                        f"Search for data related to rare disease '{disease}' "
                        f"across GA4GH federated sources.\n\n"
                        f"Phenotypes: {phenotypes or 'not specified'}\n\n"
                        f"Use beacon_query to search for matching individuals, "
                        f"drs_get_object to access relevant datasets, and "
                        f"data_connect_search to query clinical data tables. "
                        f"Summarize available data, cohort sizes, and access requirements."
                    ),
                ),
            )
        ],
    )


def _workflow_submit(args: dict) -> GetPromptResult:
    workflow_url = args.get("workflow_url", "")
    server_url = args.get("server_url", "")
    workflow_type = args.get("workflow_type", "CWL")
    return GetPromptResult(
        description=f"Submit {workflow_type} workflow",
        messages=[
            PromptMessage(
                role="user",
                content=TextContent(
                    type="text",
                    text=(
                        f"Submit workflow to WES server and monitor execution.\n\n"
                        f"Workflow: {workflow_url}\n"
                        f"Server: {server_url}\n"
                        f"Type: {workflow_type}\n\n"
                        f"Use wes_submit_run to submit the workflow, then monitor "
                        f"progress. Report run ID, status, and any errors."
                    ),
                ),
            )
        ],
    )


def _compliance_report(args: dict) -> GetPromptResult:
    server_url = args.get("server_url", "")
    spec = args.get("spec", "")
    return GetPromptResult(
        description=f"GA4GH compliance report for {spec}",
        messages=[
            PromptMessage(
                role="user",
                content=TextContent(
                    type="text",
                    text=(
                        f"Run GA4GH compliance tests against the server.\n\n"
                        f"Server: {server_url}\n"
                        f"Specification: {spec}\n\n"
                        f"Test the server's conformance to the GA4GH {spec} specification. "
                        f"Report which endpoints respond correctly, which fail, "
                        f"and provide recommendations for achieving full compliance."
                    ),
                ),
            )
        ],
    )


_PROMPT_RENDERERS = {
    "find_variants": _find_variants,
    "patient_summary": _patient_summary,
    "rare_disease_search": _rare_disease_search,
    "workflow_submit": _workflow_submit,
    "compliance_report": _compliance_report,
}
