import asyncio
import sys
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationOptions
import mcp.server.stdio
from mcp.types import Tool, TextContent

from .core import evaluate_semantic_assertion

# Initialize MCP Server
app = Server("pytest-semantic-mcp")

@app.list_tools()
async def list_tools() -> list[Tool]:
    """List available tools."""
    return [
        Tool(
            name="evaluate_semantic_assertion",
            description="Evaluates whether an execution trace journey matches the developer's intent using an LLM. Internally cached for speed.",
            inputSchema={
                "type": "object",
                "properties": {
                    "intent": {"type": "string", "description": "The plain English intent."},
                    "trace_log": {"type": "string", "description": "The stringified traceback log output generated by sys.monitoring"},
                },
                "required": ["intent", "trace_log"]
            }
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    """Execute a tool."""
    if name == "evaluate_semantic_assertion":
        
        evaluation = evaluate_semantic_assertion(
            intent=arguments["intent"],
            trace_log=arguments["trace_log"],
        )
        
        return [
            TextContent(
                type="text",
                text=f"Passed: {evaluation.passed}\nReason: {evaluation.reason}"
            )
        ]
        
    raise ValueError(f"Unknown tool: {name}")

async def main():
    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await app.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="pytest-semantic-mcp",
                server_version="0.1.0",
                capabilities=app.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                )
            )
        )

def run():
    asyncio.run(main())

if __name__ == "__main__":  # pragma: no cover
    run()
