import json
import time
import uuid
from typing import Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from modules.mcp.models import MCPToolPolicy, MCPExecutionLog
from modules.mcp.tools_registry import PLATFORM_MCP_TOOLS


class MCPServer:
    """
    Standard Model Context Protocol (MCP) Server implementing JSON-RPC 2.0.
    Enables external AI clients (Claude Desktop, Cursor, Custom Agents) to discover
    and execute cloud platform tools with tenant isolation and approval policies.
    """

    PROTOCOL_VERSION = "2024-11-05"
    SERVER_NAME = "SuperBot-MCP-Cloud"
    SERVER_VERSION = "1.0.0"

    def __init__(self, session: AsyncSession, tenant_id: uuid.UUID, caller_identity: str = "external_ai"):
        self.session = session
        self.tenant_id = tenant_id
        self.caller_identity = caller_identity

    async def handle_jsonrpc(self, request_payload: dict[str, Any]) -> dict[str, Any]:
        req_id = request_payload.get("id")
        method = request_payload.get("method")
        params = request_payload.get("params") or {}

        if request_payload.get("jsonrpc") != "2.0" or not method:
            return self._error_response(req_id, -32600, "Invalid Request: missing jsonrpc='2.0' or method")

        try:
            if method == "initialize":
                return self._handle_initialize(req_id, params)
            elif method == "tools/list":
                return await self._handle_tools_list(req_id, params)
            elif method == "tools/call":
                return await self._handle_tools_call(req_id, params)
            elif method == "ping":
                return {"jsonrpc": "2.0", "id": req_id, "result": {}}
            else:
                return self._error_response(req_id, -32601, f"Method not found: '{method}'")
        except Exception as exc:
            return self._error_response(req_id, -32603, f"Internal JSON-RPC error: {str(exc)}")

    def _handle_initialize(self, req_id: Any, params: dict[str, Any]) -> dict[str, Any]:
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "protocolVersion": self.PROTOCOL_VERSION,
                "capabilities": {
                    "tools": {
                        "listChanged": True,
                    },
                    "resources": {},
                    "prompts": {},
                },
                "serverInfo": {
                    "name": self.SERVER_NAME,
                    "version": self.SERVER_VERSION,
                },
            },
        }

    async def _handle_tools_list(self, req_id: Any, params: dict[str, Any]) -> dict[str, Any]:
        # Check tenant policies for disabled tools
        disabled_tools = await self._get_disabled_tools()

        tools_list = []
        for name, tool in PLATFORM_MCP_TOOLS.items():
            if name in disabled_tools:
                continue
            tools_list.append({
                "name": tool.name,
                "description": tool.description,
                "inputSchema": tool.input_schema,
            })

        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "tools": tools_list,
            },
        }

    async def _handle_tools_call(self, req_id: Any, params: dict[str, Any]) -> dict[str, Any]:
        tool_name = params.get("name")
        arguments = params.get("arguments") or {}

        if not tool_name or tool_name not in PLATFORM_MCP_TOOLS:
            return self._error_response(req_id, -32602, f"Unknown tool: '{tool_name}'")

        tool = PLATFORM_MCP_TOOLS[tool_name]

        # 1. Policy & Authorization Check
        policy = await self._get_tool_policy(tool_name)
        if policy and not policy.is_enabled:
            return self._mcp_tool_result(
                req_id,
                content=[{"type": "text", "text": f"Tool '{tool_name}' is disabled by tenant security policy."}],
                is_error=True,
            )

        # 2. Check if dangerous and requires human approval
        requires_approval = (policy.requires_approval if policy else tool.is_dangerous)
        if requires_approval:
            exec_log = MCPExecutionLog(
                tenant_id=self.tenant_id,
                tool_name=tool_name,
                caller_type="external_ai",
                caller_identity=self.caller_identity,
                input_arguments=arguments,
                status="approval_pending",
                approval_status="pending",
                execution_time_ms=0,
            )
            self.session.add(exec_log)
            await self.session.commit()

            return self._mcp_tool_result(
                req_id,
                content=[{
                    "type": "text",
                    "text": f"Tool '{tool_name}' requires human approval. Execution requested with ID: {exec_log.id}. A tenant administrator must approve this action.",
                }],
                is_error=False,
            )

        # 3. Direct Execution
        start_time = time.time()
        error_msg: Optional[str] = None
        output_result: Optional[dict[str, Any]] = None
        status = "success"

        try:
            output_result = await tool.handler(self.tenant_id, arguments, self.session)
        except Exception as exc:
            status = "error"
            error_msg = str(exc)
            output_result = {"error": str(exc)}

        elapsed_ms = int((time.time() - start_time) * 1000)

        # 4. Log execution in audit table
        exec_log = MCPExecutionLog(
            tenant_id=self.tenant_id,
            tool_name=tool_name,
            caller_type="external_ai",
            caller_identity=self.caller_identity,
            input_arguments=arguments,
            output_result=output_result,
            status=status,
            execution_time_ms=elapsed_ms,
            approval_status="auto_approved",
            error_message=error_msg,
        )
        self.session.add(exec_log)
        await self.session.commit()

        is_error = status == "error" or (output_result and "error" in output_result)
        return self._mcp_tool_result(
            req_id,
            content=[{
                "type": "text",
                "text": json.dumps(output_result, indent=2),
            }],
            is_error=is_error,
        )

    def _mcp_tool_result(self, req_id: Any, content: list[dict[str, Any]], is_error: bool = False) -> dict[str, Any]:
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "content": content,
                "isError": is_error,
            },
        }

    def _error_response(self, req_id: Any, code: int, message: str) -> dict[str, Any]:
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "error": {
                "code": code,
                "message": message,
            },
        }

    async def _get_disabled_tools(self) -> set[str]:
        query = select(MCPToolPolicy.tool_name).where(
            MCPToolPolicy.tenant_id == self.tenant_id,
            MCPToolPolicy.is_enabled.is_(False),
        )
        res = await self.session.execute(query)
        return set(res.scalars().all())

    async def _get_tool_policy(self, tool_name: str) -> Optional[MCPToolPolicy]:
        query = select(MCPToolPolicy).where(
            MCPToolPolicy.tenant_id == self.tenant_id,
            MCPToolPolicy.tool_name == tool_name,
        )
        res = await self.session.execute(query)
        return res.scalar_one_or_none()
