"""
MCP server for ADP Deep Analysis.
Exposes one tool to Claude: deep_analysis
"""

import asyncio
import logging

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool

from adp_mcp.client import ADPClient
from adp_mcp.formatter import format_analysis

logger = logging.getLogger(__name__)

server = Server("adp-deep-analysis")


@server.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="deep_analysis",
            description=(
                "Analyze a legal document for citation accuracy. "
                "Verifies every case, statute, and rule citation exists, then uses "
                "multiple independent AI models to assess whether each citation supports "
                "the legal argument it's cited for. Florida state court filings only."
            ),
            inputSchema={
                "type": "object",
                "properties": {
                    "document_text": {
                        "type": "string",
                        "description": "Full text of the legal document to analyze",
                    },
                    "document_name": {
                        "type": "string",
                        "description": "Filename for reference (optional)",
                        "default": "Untitled",
                    },
                },
                "required": ["document_text"],
            },
        )
    ]


@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name != "deep_analysis":
        return [TextContent(type="text", text=f"Unknown tool: {name}")]

    document_text = arguments.get("document_text", "")
    document_name = arguments.get("document_name", "Untitled")

    if not document_text.strip():
        return [TextContent(type="text", text="Error: document_text is empty.")]

    try:
        client = ADPClient()
        raw_result = await client.analyze(document_text, document_name)
        formatted = format_analysis(raw_result)
        return [TextContent(type="text", text=formatted)]
    except Exception as exc:
        logger.error("Deep analysis failed: %s", exc, exc_info=True)
        return [TextContent(type="text", text=f"Error running deep analysis: {exc}")]


async def _async_main():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())


def main():
    """Entry point for the adp-mcp console script."""
    asyncio.run(_async_main())


if __name__ == "__main__":
    main()
