import uuid
from typing import Any, Optional
from sqlalchemy import (
    Boolean,
    Float,
    ForeignKey,
    Index,
    Integer,
    JSON,
    String,
    Text,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from infrastructure.database.base import (
    Base,
    UUIDPrimaryKeyMixin,
    TimestampMixin,
    TenantMixin,
)


class TenantAIKey(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Tenant-provided API keys for OpenRouter or OpenAI, encrypted with AES-256-GCM."""
    __tablename__ = "tenant_ai_keys"

    provider: Mapped[str] = mapped_column(String(50), nullable=False)  # openai | openrouter
    key_name: Mapped[str] = mapped_column(String(100), nullable=False)
    encrypted_api_key: Mapped[str] = mapped_column(String(500), nullable=False)
    key_version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    masked_key: Mapped[str] = mapped_column(String(50), nullable=False)


class AIAgent(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Configured AI assistant with system prompt, temperature, and provider settings."""
    __tablename__ = "ai_agents"

    bot_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bots.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    provider: Mapped[str] = mapped_column(String(50), default="openai", nullable=False)
    model: Mapped[str] = mapped_column(String(100), default="gpt-4o-mini", nullable=False)
    system_prompt: Mapped[str] = mapped_column(Text, nullable=False)
    temperature: Mapped[float] = mapped_column(Float, default=0.7, nullable=False)
    max_tokens: Mapped[int] = mapped_column(Integer, default=1000, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    tools_config: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)

    conversations: Mapped[list["AIConversation"]] = relationship(
        "AIConversation", back_populates="agent", cascade="all, delete-orphan"
    )


class AIConversation(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Multi-turn conversation session tied to an AI agent and Telegram chat/user."""
    __tablename__ = "ai_conversations"

    agent_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("ai_agents.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    bot_user_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bot_users.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    session_id: Mapped[str] = mapped_column(String(100), index=True, nullable=False)
    title: Mapped[str] = mapped_column(String(255), default="New Conversation", nullable=False)
    total_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    total_cost_microcents: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

    agent: Mapped["AIAgent"] = relationship("AIAgent", back_populates="conversations")
    messages: Mapped[list["AIMessage"]] = relationship(
        "AIMessage", back_populates="conversation", cascade="all, delete-orphan", order_by="AIMessage.created_at"
    )


class AIMessage(Base, UUIDPrimaryKeyMixin, TimestampMixin):
    """Individual message in a conversation thread."""
    __tablename__ = "ai_messages"

    conversation_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("ai_conversations.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    role: Mapped[str] = mapped_column(String(20), nullable=False)  # system | user | assistant | tool
    content: Mapped[str] = mapped_column(Text, nullable=False)
    prompt_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    completion_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    total_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    latency_ms: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

    conversation: Mapped["AIConversation"] = relationship("AIConversation", back_populates="messages")


class AIUsageLog(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Auditable log of token consumption and cost for billing analysis and quotas."""
    __tablename__ = "ai_usage_logs"

    agent_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("ai_agents.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    conversation_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("ai_conversations.id", ondelete="SET NULL"),
        nullable=True,
    )
    provider: Mapped[str] = mapped_column(String(50), nullable=False)
    model: Mapped[str] = mapped_column(String(100), nullable=False)
    prompt_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    completion_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    total_tokens: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    cost_microcents: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
