from sqlalchemy import BigInteger, Boolean, String
from sqlalchemy.orm import Mapped, mapped_column
from app.core.models.base import Base, TimestampMixin


class AiProfile(Base, TimestampMixin):
    """AI 服务配置 — 由 superadmin 建立，可被多个租户共用"""

    __tablename__ = "ai_profiles"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="展示名称，如 平台默认-DeepSeek")
    provider: Mapped[str] = mapped_column(String(20), nullable=False, comment="deepseek/minimax/ollama/openai_compat")
    api_key: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="API Key，敏感信息")
    base_url: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="服务地址，为空则用 provider 默认值")
    model: Mapped[str | None] = mapped_column(String(100), nullable=True, comment="模型名称，为空则用 provider 默认值")
    is_default: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, comment="租户未分配时的兜底配置")
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, comment="是否启用")

    def to_ai_extra(self) -> dict:
        """转换成 call_ai/call_ai_stream 期望的 extra dict 形状"""
        return {
            "ai_provider": self.provider,
            "ai_api_key": self.api_key,
            "ai_base_url": self.base_url,
            "ai_model": self.model,
        }

    def __repr__(self) -> str:
        return f"<AiProfile id={self.id} name={self.name!r} provider={self.provider}>"
