from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship

from app.models.base import Base, TimestampMixin


class UserModelConfig(Base, TimestampMixin):
    __tablename__ = "user_model_configs"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
    name = Column(String(255), nullable=False)
    provider = Column(String(64), nullable=False, default="dashscope")
    api_key = Column(Text, nullable=False)
    api_base = Column(String(512), nullable=True)
    chat_model = Column(String(128), nullable=False)
    embedding_model = Column(String(128), nullable=False)
    is_active = Column(Boolean, default=True, nullable=False, index=True)
    last_used_at = Column(DateTime(timezone=True), nullable=True)

    user = relationship("User", back_populates="model_configs")

    @property
    def has_api_key(self) -> bool:
        return bool((self.api_key or "").strip())

    @property
    def api_key_masked(self) -> str:
        value = (self.api_key or "").strip()
        if not value:
            return ""
        if len(value) <= 10:
            return "*" * len(value)
        return f"{value[:4]}{'*' * 8}{value[-4:]}"
