import uuid
from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey, JSON
from sqlalchemy import Uuid as UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin

if TYPE_CHECKING:
    from src.models.user import User


class UserConfig(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "user_configs"

    user_id: Mapped[uuid.UUID] = mapped_column(
        UUID(), ForeignKey("users.id"), nullable=False, unique=True
    )
    config: Mapped[dict[str, object]] = mapped_column(
        JSON, default=dict, nullable=False
    )

    user: Mapped["User"] = relationship(back_populates="user_config")

    @property
    def default_profile_id(self) -> uuid.UUID | None:
        """Return the legacy global default profile ID from config JSON."""
        profile_id = self.config.get("default_profile_id")
        if isinstance(profile_id, str):
            return uuid.UUID(profile_id)
        return None

    @default_profile_id.setter
    def default_profile_id(self, value: uuid.UUID | None) -> None:
        if value is not None:
            self.config["default_profile_id"] = str(value)
        elif "default_profile_id" in self.config:
            del self.config["default_profile_id"]

    @property
    def default_profiles(self) -> dict[str, str]:
        """Return per-tool-type default profile IDs from config JSON."""
        value = self.config.get("default_profiles", {})
        if isinstance(value, dict):
            return {str(k): str(v) for k, v in value.items()}
        return {}

    @default_profiles.setter
    def default_profiles(self, value: dict[str, str]) -> None:
        self.config["default_profiles"] = value
