import time
import uuid
from datetime import datetime, timezone
from typing import Any, Optional, Sequence
from sqlalchemy.ext.asyncio import AsyncSession
from core.encryption import encrypt_string, decrypt_string
from core.exceptions import NotFoundError, ValidationError, ForbiddenError
from modules.mcp.client import MCPClient
from modules.mcp.models import MCPServerConnection, MCPToolPolicy, MCPExecutionLog
from modules.mcp.repository import MCPRepository
from modules.mcp.schemas import (
    RegisterMCPServerRequest,
    UpdateToolPolicyRequest,
    ToolDefinitionResponse,
)
from modules.mcp.server import MCPServer
from modules.mcp.tools_registry import PLATFORM_MCP_TOOLS


class MCPService:
    def __init__(self, session: AsyncSession):
        self.session = session
        self.repo = MCPRepository(session)
        self.client = MCPClient()

    async def handle_jsonrpc(
        self,
        payload: dict[str, Any],
        tenant_id: uuid.UUID,
        caller_identity: str = "external_ai",
    ) -> dict[str, Any]:
        server = MCPServer(self.session, tenant_id, caller_identity=caller_identity)
        return await server.handle_jsonrpc(payload)

    async def register_server(
        self, tenant_id: uuid.UUID, data: RegisterMCPServerRequest
    ) -> MCPServerConnection:
        existing = await self.repo.get_server_by_slug(data.slug, tenant_id)
        if existing:
            raise ValidationError(f"MCP Server connection with slug '{data.slug}' already exists.")

        encrypted_token: Optional[str] = None
        if data.auth_token:
            cipher, version = encrypt_string(data.auth_token)
            encrypted_token = cipher

        server = MCPServerConnection(
            tenant_id=tenant_id,
            name=data.name,
            slug=data.slug,
            transport_type=data.transport_type,
            endpoint_url=data.endpoint_url,
            encrypted_auth_token=encrypted_token,
            is_active=True,
            status="connected",
            discovered_tools=[],
        )
        server = await self.repo.create_server(server)

        # Attempt initial tool discovery sync (non-blocking if server is offline)
        try:
            tools = await self.client.discover_tools(data.endpoint_url, data.auth_token)
            server.discovered_tools = tools
            server.last_synced_at = datetime.now(timezone.utc)
            server.status = "connected"
        except Exception:
            server.status = "disconnected"

        await self.session.flush()
        return server

    async def list_servers(self, tenant_id: uuid.UUID) -> Sequence[MCPServerConnection]:
        return await self.repo.list_servers(tenant_id)

    async def get_server(self, server_id: uuid.UUID, tenant_id: uuid.UUID) -> MCPServerConnection:
        server = await self.repo.get_server_by_id(server_id, tenant_id)
        if not server:
            raise NotFoundError(f"MCP server connection '{server_id}' not found.")
        return server

    async def delete_server(self, server_id: uuid.UUID, tenant_id: uuid.UUID) -> None:
        server = await self.get_server(server_id, tenant_id)
        await self.repo.delete_server(server)

    async def sync_server_tools(self, server_id: uuid.UUID, tenant_id: uuid.UUID) -> MCPServerConnection:
        server = await self.get_server(server_id, tenant_id)

        plain_token: Optional[str] = None
        if server.encrypted_auth_token:
            plain_token = decrypt_string(server.encrypted_auth_token, 1)

        try:
            tools = await self.client.discover_tools(server.endpoint_url, plain_token)
            server.discovered_tools = tools
            server.last_synced_at = datetime.now(timezone.utc)
            server.status = "connected"
        except Exception as exc:
            server.status = "error"
            raise ValidationError(f"Failed to sync tools from MCP server: {str(exc)}")

        await self.session.flush()
        return server

    async def list_tools(self, tenant_id: uuid.UUID) -> list[ToolDefinitionResponse]:
        """Returns all platform core tools plus tools discovered from external servers, with tenant policies."""
        policies_list = await self.repo.list_policies(tenant_id)
        policies_map = {p.tool_name: p for p in policies_list}

        results: list[ToolDefinitionResponse] = []

        # 1. Platform Core Tools
        for name, tool in PLATFORM_MCP_TOOLS.items():
            policy = policies_map.get(name)
            is_enabled = policy.is_enabled if policy else True
            requires_approval = policy.requires_approval if policy else tool.is_dangerous

            results.append(
                ToolDefinitionResponse(
                    name=tool.name,
                    description=tool.description,
                    input_schema=tool.input_schema,
                    is_dangerous=tool.is_dangerous,
                    source="platform_core",
                    requires_approval=requires_approval,
                    is_enabled=is_enabled,
                )
            )

        # 2. External Server Tools
        servers = await self.repo.list_servers(tenant_id)
        for s in servers:
            for ext_tool in (s.discovered_tools or []):
                t_name = f"{s.slug}.{ext_tool.get('name')}"
                policy = policies_map.get(t_name)
                is_enabled = policy.is_enabled if policy else True
                requires_approval = policy.requires_approval if policy else False

                results.append(
                    ToolDefinitionResponse(
                        name=t_name,
                        description=ext_tool.get("description", f"Tool from {s.name}"),
                        input_schema=ext_tool.get("inputSchema", {}),
                        is_dangerous=False,
                        source="external_server",
                        requires_approval=requires_approval,
                        is_enabled=is_enabled,
                    )
                )

        return results

    async def update_policy(
        self, tenant_id: uuid.UUID, tool_name: str, data: UpdateToolPolicyRequest
    ) -> MCPToolPolicy:
        return await self.repo.upsert_policy(
            tenant_id=tenant_id,
            tool_name=tool_name,
            is_enabled=data.is_enabled,
            requires_approval=data.requires_approval,
            rate_limit_per_minute=data.rate_limit_per_minute,
            allowed_roles=data.allowed_roles,
        )

    async def list_policies(self, tenant_id: uuid.UUID) -> Sequence[MCPToolPolicy]:
        return await self.repo.list_policies(tenant_id)

    async def list_execution_logs(
        self, tenant_id: uuid.UUID, tool_name: Optional[str] = None, limit: int = 50, offset: int = 0
    ) -> Sequence[MCPExecutionLog]:
        return await self.repo.list_execution_logs(
            tenant_id=tenant_id, tool_name=tool_name, limit=limit, offset=offset
        )

    async def approve_execution(
        self, execution_id: uuid.UUID, tenant_id: uuid.UUID, approver_user_id: uuid.UUID
    ) -> MCPExecutionLog:
        log = await self.repo.get_execution_log(execution_id, tenant_id)
        if not log:
            raise NotFoundError(f"Execution record '{execution_id}' not found.")

        if log.status != "approval_pending":
            raise ValidationError(f"Execution is in '{log.status}' state; cannot approve.")

        tool = PLATFORM_MCP_TOOLS.get(log.tool_name)
        if not tool:
            raise ValidationError(f"Tool '{log.tool_name}' no longer exists.")

        start_time = time.time()
        try:
            output = await tool.handler(tenant_id, log.input_arguments, self.session)
            log.output_result = output
            log.status = "success"
        except Exception as exc:
            log.status = "error"
            log.error_message = str(exc)
            log.output_result = {"error": str(exc)}

        log.execution_time_ms = int((time.time() - start_time) * 1000)
        log.approval_status = "approved"
        log.approver_user_id = approver_user_id
        await self.session.flush()
        return log

    async def reject_execution(
        self, execution_id: uuid.UUID, tenant_id: uuid.UUID, approver_user_id: uuid.UUID
    ) -> MCPExecutionLog:
        log = await self.repo.get_execution_log(execution_id, tenant_id)
        if not log:
            raise NotFoundError(f"Execution record '{execution_id}' not found.")

        log.status = "rejected"
        log.approval_status = "rejected"
        log.approver_user_id = approver_user_id
        await self.session.flush()
        return log
