import uuid
from typing import Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import ForbiddenError, NotFoundError, ValidationError
from core.encryption import decrypt_string, encrypt_string
from modules.ai.models import AIAgent, TenantAIKey
from modules.ai.providers.factory import AIProviderFactory
from modules.ai.repository import AIRepository
from modules.ai.schemas import (
    AIAgentResponse,
    AIConversationResponse,
    AIMessageResponse,
    AIUsageSummaryResponse,
    ChatRequest,
    ChatResponse,
    CreateAIAgentRequest,
    CreateTenantAIKeyRequest,
    TenantAIKeyResponse,
    UpdateAIAgentRequest,
)
from modules.billing.entitlement_service import EntitlementService


class AIService:
    """Manages AI providers, encrypted keys, agents, and conversational sessions."""

    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = AIRepository(db)
        self.entitlements = EntitlementService(db)

    # --- Tenant API Keys (AES-256-GCM Encrypted) ---
    async def add_tenant_api_key(
        self,
        tenant_id: uuid.UUID,
        req: CreateTenantAIKeyRequest,
    ) -> TenantAIKeyResponse:
        # Check plan entitlement
        await self.entitlements.check_feature_access(tenant_id, "ai_enabled")

        encrypted_key, version = encrypt_string(req.api_key)
        # Create masked representation (e.g., sk-...4a1b)
        masked = f"{req.api_key[:4]}...{req.api_key[-4:]}" if len(req.api_key) > 8 else "***"

        key = await self.repo.save_tenant_key(
            tenant_id=tenant_id,
            provider=req.provider.lower().strip(),
            key_name=req.key_name,
            encrypted_api_key=encrypted_key,
            key_version=version,
            masked_key=masked,
        )
        return TenantAIKeyResponse.model_validate(key)

    async def list_tenant_api_keys(self, tenant_id: uuid.UUID) -> list[TenantAIKeyResponse]:
        keys = await self.repo.list_tenant_keys(tenant_id)
        return [TenantAIKeyResponse.model_validate(k) for k in keys]

    async def delete_tenant_api_key(self, tenant_id: uuid.UUID, key_id: uuid.UUID) -> bool:
        return await self.repo.delete_tenant_key(tenant_id, key_id)

    async def _get_decrypted_key(self, tenant_id: uuid.UUID, provider: str) -> Optional[str]:
        key_record = await self.repo.get_tenant_key(tenant_id, provider)
        if key_record:
            return decrypt_string(key_record.encrypted_api_key, key_record.key_version)
        return None

    # --- Models Catalog ---
    def list_supported_models(self, provider: str = "openai") -> list[dict[str, Any]]:
        p = AIProviderFactory.get_provider(provider)
        return p.list_supported_models()

    # --- AI Agents ---
    async def create_agent(
        self,
        tenant_id: uuid.UUID,
        req: CreateAIAgentRequest,
    ) -> AIAgentResponse:
        await self.entitlements.check_feature_access(tenant_id, "ai_enabled")

        agent = await self.repo.create_agent(
            tenant_id=tenant_id,
            name=req.name,
            provider=req.provider.lower().strip(),
            model=req.model,
            system_prompt=req.system_prompt,
            temperature=req.temperature,
            max_tokens=req.max_tokens,
            bot_id=req.bot_id,
            tools_config=req.tools_config,
        )
        return AIAgentResponse.model_validate(agent)

    async def get_agent(self, tenant_id: uuid.UUID, agent_id: uuid.UUID) -> AIAgentResponse:
        agent = await self.repo.get_agent_by_id(agent_id, tenant_id)
        if not agent:
            raise NotFoundError("AI Agent not found")
        return AIAgentResponse.model_validate(agent)

    async def list_agents(self, tenant_id: uuid.UUID) -> list[AIAgentResponse]:
        agents = await self.repo.list_agents(tenant_id)
        return [AIAgentResponse.model_validate(a) for a in agents]

    async def update_agent(
        self,
        tenant_id: uuid.UUID,
        agent_id: uuid.UUID,
        req: UpdateAIAgentRequest,
    ) -> AIAgentResponse:
        agent = await self.repo.get_agent_by_id(agent_id, tenant_id)
        if not agent:
            raise NotFoundError("AI Agent not found")

        updated = await self.repo.update_agent(
            agent,
            name=req.name,
            model=req.model,
            system_prompt=req.system_prompt,
            temperature=req.temperature,
            max_tokens=req.max_tokens,
            is_active=req.is_active,
        )
        return AIAgentResponse.model_validate(updated)

    async def delete_agent(self, tenant_id: uuid.UUID, agent_id: uuid.UUID) -> None:
        agent = await self.repo.get_agent_by_id(agent_id, tenant_id)
        if not agent:
            raise NotFoundError("AI Agent not found")
        await self.repo.delete_agent(agent)

    # --- Conversation & Chat Interaction ---
    async def chat(
        self,
        tenant_id: uuid.UUID,
        agent_id: uuid.UUID,
        req: ChatRequest,
    ) -> ChatResponse:
        """
        Executes a multi-turn chat completion, maintaining message history and logging token costs.
        """
        await self.entitlements.check_feature_access(tenant_id, "ai_enabled")

        agent = await self.repo.get_agent_by_id(agent_id, tenant_id)
        if not agent or not agent.is_active:
            raise ValidationError("AI Agent is not active or does not exist")

        session_id = req.session_id or f"sess_{uuid.uuid4().hex[:12]}"
        conv = await self.repo.get_or_create_conversation(
            tenant_id=tenant_id,
            agent_id=agent.id,
            session_id=session_id,
            title=f"Chat: {req.message[:30]}...",
        )

        # 1. Save incoming user message
        await self.repo.save_message(
            conversation_id=conv.id,
            role="user",
            content=req.message,
        )

        # 2. Build context messages (system prompt + past history)
        history_msgs = await self.repo.list_conversation_messages(conv.id, limit=20)
        messages_payload = [{"role": "system", "content": agent.system_prompt}]
        for m in history_msgs:
            messages_payload.append({"role": m.role, "content": m.content})

        # 3. Retrieve decrypted tenant API key (or fallback to platform default)
        api_key = await self._get_decrypted_key(tenant_id, agent.provider)

        # 4. Generate LLM completion
        provider = AIProviderFactory.get_provider(agent.provider, api_key=api_key)
        res = await provider.generate_completion(
            messages=messages_payload,
            model=agent.model,
            temperature=agent.temperature,
            max_tokens=agent.max_tokens,
            api_key=api_key,
        )

        # 5. Save assistant reply
        await self.repo.save_message(
            conversation_id=conv.id,
            role="assistant",
            content=res.content,
            prompt_tokens=res.prompt_tokens,
            completion_tokens=res.completion_tokens,
            total_tokens=res.total_tokens,
            latency_ms=res.latency_ms,
        )

        # 6. Update conversation totals
        conv.total_tokens += res.total_tokens
        conv.total_cost_microcents += res.cost_microcents
        await self.db.commit()

        # 7. Record usage audit log
        await self.repo.record_usage(
            tenant_id=tenant_id,
            agent_id=agent.id,
            conversation_id=conv.id,
            provider=agent.provider,
            model=res.model,
            prompt_tokens=res.prompt_tokens,
            completion_tokens=res.completion_tokens,
            total_tokens=res.total_tokens,
            cost_microcents=res.cost_microcents,
        )

        cost_cents = round(float(res.cost_microcents) / 100_000, 4)
        return ChatResponse(
            conversation_id=conv.id,
            role="assistant",
            content=res.content,
            model=res.model,
            prompt_tokens=res.prompt_tokens,
            completion_tokens=res.completion_tokens,
            total_tokens=res.total_tokens,
            cost_cents=cost_cents,
            latency_ms=res.latency_ms,
        )

    async def get_usage_summary(self, tenant_id: uuid.UUID) -> AIUsageSummaryResponse:
        summary = await self.repo.get_tenant_usage_summary(tenant_id)
        return AIUsageSummaryResponse(**summary)
