import uuid
from typing import Any, Optional
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from modules.ai.models import (
    AIAgent,
    AIConversation,
    AIMessage,
    AIUsageLog,
    TenantAIKey,
)


class AIRepository:
    def __init__(self, db: AsyncSession):
        self.db = db

    # --- Tenant API Keys ---
    async def get_tenant_key(self, tenant_id: uuid.UUID, provider: str) -> Optional[TenantAIKey]:
        res = await self.db.execute(
            select(TenantAIKey).where(
                TenantAIKey.tenant_id == tenant_id,
                TenantAIKey.provider == provider,
                TenantAIKey.is_active.is_(True),
            )
        )
        return res.scalar_one_or_none()

    async def list_tenant_keys(self, tenant_id: uuid.UUID) -> list[TenantAIKey]:
        res = await self.db.execute(
            select(TenantAIKey).where(TenantAIKey.tenant_id == tenant_id).order_by(TenantAIKey.created_at.desc())
        )
        return list(res.scalars().all())

    async def save_tenant_key(
        self,
        tenant_id: uuid.UUID,
        provider: str,
        key_name: str,
        encrypted_api_key: str,
        key_version: int,
        masked_key: str,
    ) -> TenantAIKey:
        key = TenantAIKey(
            id=uuid.uuid4(),
            tenant_id=tenant_id,
            provider=provider,
            key_name=key_name,
            encrypted_api_key=encrypted_api_key,
            key_version=key_version,
            is_active=True,
            masked_key=masked_key,
        )
        self.db.add(key)
        await self.db.commit()
        await self.db.refresh(key)
        return key

    async def delete_tenant_key(self, tenant_id: uuid.UUID, key_id: uuid.UUID) -> bool:
        res = await self.db.execute(
            select(TenantAIKey).where(TenantAIKey.id == key_id, TenantAIKey.tenant_id == tenant_id)
        )
        key = res.scalar_one_or_none()
        if key:
            await self.db.delete(key)
            await self.db.commit()
            return True
        return False

    # --- AI Agents ---
    async def create_agent(
        self,
        tenant_id: uuid.UUID,
        name: str,
        provider: str,
        model: str,
        system_prompt: str,
        temperature: float,
        max_tokens: int,
        bot_id: Optional[uuid.UUID] = None,
        tools_config: Optional[dict[str, Any]] = None,
    ) -> AIAgent:
        agent = AIAgent(
            id=uuid.uuid4(),
            tenant_id=tenant_id,
            bot_id=bot_id,
            name=name,
            provider=provider,
            model=model,
            system_prompt=system_prompt,
            temperature=temperature,
            max_tokens=max_tokens,
            is_active=True,
            tools_config=tools_config,
        )
        self.db.add(agent)
        await self.db.commit()
        await self.db.refresh(agent)
        return agent

    async def get_agent_by_id(self, agent_id: uuid.UUID, tenant_id: Optional[uuid.UUID] = None) -> Optional[AIAgent]:
        stmt = select(AIAgent).where(AIAgent.id == agent_id)
        if tenant_id:
            stmt = stmt.where(AIAgent.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        return res.scalar_one_or_none()

    async def list_agents(self, tenant_id: uuid.UUID) -> list[AIAgent]:
        res = await self.db.execute(
            select(AIAgent).where(AIAgent.tenant_id == tenant_id).order_by(AIAgent.created_at.desc())
        )
        return list(res.scalars().all())

    async def update_agent(self, agent: AIAgent, **updates: Any) -> AIAgent:
        for k, v in updates.items():
            if v is not None:
                setattr(agent, k, v)
        await self.db.commit()
        await self.db.refresh(agent)
        return agent

    async def delete_agent(self, agent: AIAgent) -> None:
        await self.db.delete(agent)
        await self.db.commit()

    # --- Conversations & Messages ---
    async def get_or_create_conversation(
        self,
        tenant_id: uuid.UUID,
        agent_id: uuid.UUID,
        session_id: str,
        title: str = "New Conversation",
    ) -> AIConversation:
        res = await self.db.execute(
            select(AIConversation).where(
                AIConversation.tenant_id == tenant_id,
                AIConversation.agent_id == agent_id,
                AIConversation.session_id == session_id,
            )
        )
        conv = res.scalar_one_or_none()
        if not conv:
            conv = AIConversation(
                id=uuid.uuid4(),
                tenant_id=tenant_id,
                agent_id=agent_id,
                session_id=session_id,
                title=title,
                total_tokens=0,
                total_cost_microcents=0,
            )
            self.db.add(conv)
            await self.db.commit()
            await self.db.refresh(conv)
        return conv

    async def list_conversation_messages(self, conversation_id: uuid.UUID, limit: int = 50) -> list[AIMessage]:
        res = await self.db.execute(
            select(AIMessage)
            .where(AIMessage.conversation_id == conversation_id)
            .order_by(AIMessage.created_at.asc())
            .limit(limit)
        )
        return list(res.scalars().all())

    async def save_message(
        self,
        conversation_id: uuid.UUID,
        role: str,
        content: str,
        prompt_tokens: int = 0,
        completion_tokens: int = 0,
        total_tokens: int = 0,
        latency_ms: int = 0,
    ) -> AIMessage:
        msg = AIMessage(
            id=uuid.uuid4(),
            conversation_id=conversation_id,
            role=role,
            content=content,
            prompt_tokens=prompt_tokens,
            completion_tokens=completion_tokens,
            total_tokens=total_tokens,
            latency_ms=latency_ms,
        )
        self.db.add(msg)
        await self.db.commit()
        await self.db.refresh(msg)
        return msg

    async def record_usage(
        self,
        tenant_id: uuid.UUID,
        agent_id: uuid.UUID,
        conversation_id: uuid.UUID,
        provider: str,
        model: str,
        prompt_tokens: int,
        completion_tokens: int,
        total_tokens: int,
        cost_microcents: int,
    ) -> AIUsageLog:
        log = AIUsageLog(
            id=uuid.uuid4(),
            tenant_id=tenant_id,
            agent_id=agent_id,
            conversation_id=conversation_id,
            provider=provider,
            model=model,
            prompt_tokens=prompt_tokens,
            completion_tokens=completion_tokens,
            total_tokens=total_tokens,
            cost_microcents=cost_microcents,
        )
        self.db.add(log)
        await self.db.commit()
        await self.db.refresh(log)
        return log

    async def get_tenant_usage_summary(self, tenant_id: uuid.UUID) -> dict[str, Any]:
        total_res = await self.db.execute(
            select(
                func.coalesce(func.sum(AIUsageLog.total_tokens), 0),
                func.coalesce(func.sum(AIUsageLog.cost_microcents), 0),
                func.count(AIUsageLog.id),
            ).where(AIUsageLog.tenant_id == tenant_id)
        )
        tot_tok, tot_cost, tot_req = total_res.fetchone() or (0, 0, 0)

        # Provider breakdown
        prov_res = await self.db.execute(
            select(AIUsageLog.provider, func.sum(AIUsageLog.total_tokens))
            .where(AIUsageLog.tenant_id == tenant_id)
            .group_by(AIUsageLog.provider)
        )
        breakdown = {row[0]: row[1] for row in prov_res.fetchall()}

        return {
            "total_tokens": int(tot_tok),
            "total_cost_cents": round(float(tot_cost) / 100_000, 4),
            "total_requests": int(tot_req),
            "provider_breakdown": breakdown,
        }
