import uuid
from typing import Optional, Sequence
from sqlalchemy import select, desc
from sqlalchemy.ext.asyncio import AsyncSession
from modules.mcp.models import (
    MCPServerConnection,
    MCPToolPolicy,
    MCPExecutionLog,
)


class MCPRepository:
    def __init__(self, session: AsyncSession):
        self.session = session

    async def create_server(self, server: MCPServerConnection) -> MCPServerConnection:
        self.session.add(server)
        await self.session.flush()
        return server

    async def get_server_by_id(self, server_id: uuid.UUID, tenant_id: uuid.UUID) -> Optional[MCPServerConnection]:
        query = select(MCPServerConnection).where(
            MCPServerConnection.id == server_id,
            MCPServerConnection.tenant_id == tenant_id,
        )
        res = await self.session.execute(query)
        return res.scalar_one_or_none()

    async def get_server_by_slug(self, slug: str, tenant_id: uuid.UUID) -> Optional[MCPServerConnection]:
        query = select(MCPServerConnection).where(
            MCPServerConnection.slug == slug,
            MCPServerConnection.tenant_id == tenant_id,
        )
        res = await self.session.execute(query)
        return res.scalar_one_or_none()

    async def list_servers(self, tenant_id: uuid.UUID) -> Sequence[MCPServerConnection]:
        query = (
            select(MCPServerConnection)
            .where(MCPServerConnection.tenant_id == tenant_id)
            .order_by(MCPServerConnection.created_at.desc())
        )
        res = await self.session.execute(query)
        return res.scalars().all()

    async def delete_server(self, server: MCPServerConnection) -> None:
        await self.session.delete(server)
        await self.session.flush()

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

    async def upsert_policy(
        self,
        tenant_id: uuid.UUID,
        tool_name: str,
        is_enabled: bool,
        requires_approval: bool,
        rate_limit_per_minute: int,
        allowed_roles: list[str],
    ) -> MCPToolPolicy:
        policy = await self.get_policy(tenant_id, tool_name)
        if policy:
            policy.is_enabled = is_enabled
            policy.requires_approval = requires_approval
            policy.rate_limit_per_minute = rate_limit_per_minute
            policy.allowed_roles = allowed_roles
        else:
            policy = MCPToolPolicy(
                tenant_id=tenant_id,
                tool_name=tool_name,
                is_enabled=is_enabled,
                requires_approval=requires_approval,
                rate_limit_per_minute=rate_limit_per_minute,
                allowed_roles=allowed_roles,
            )
            self.session.add(policy)
        await self.session.flush()
        return policy

    async def list_policies(self, tenant_id: uuid.UUID) -> Sequence[MCPToolPolicy]:
        query = (
            select(MCPToolPolicy)
            .where(MCPToolPolicy.tenant_id == tenant_id)
            .order_by(MCPToolPolicy.tool_name.asc())
        )
        res = await self.session.execute(query)
        return res.scalars().all()

    async def get_execution_log(self, execution_id: uuid.UUID, tenant_id: uuid.UUID) -> Optional[MCPExecutionLog]:
        query = select(MCPExecutionLog).where(
            MCPExecutionLog.id == execution_id,
            MCPExecutionLog.tenant_id == tenant_id,
        )
        res = await self.session.execute(query)
        return res.scalar_one_or_none()

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

        query = query.order_by(desc(MCPExecutionLog.created_at)).limit(limit).offset(offset)
        res = await self.session.execute(query)
        return res.scalars().all()
