from sqlalchemy import ForeignKey
from datetime import datetime, timezone
from sqlalchemy import UUID, Column, DateTime, String, JSON
from sqlalchemy.ext.mutable import MutableDict
from uuid import uuid4

from cognee.infrastructure.databases.relational import Base


class PrincipalConfiguration(Base):
    __tablename__ = "principal_configuration"

    id = Column(UUID, primary_key=True, default=uuid4)

    owner_id = Column(UUID, ForeignKey("principals.id", ondelete="CASCADE"), index=True)

    name = Column(String, unique=False, nullable=False)

    # MutableDict allows SQLAlchemy to notice key-value pair changes, without it changing a value for a key
    # wouldn't be noticed when commiting a database session
    configuration = Column(MutableDict.as_mutable(JSON))

    created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
    updated_at = Column(DateTime(timezone=True), onupdate=lambda: datetime.now(timezone.utc))

    def to_json(self) -> dict:
        return {
            "id": str(self.id),
            "ownerId": str(self.owner_id),
            "name": self.name,
            "configuration": self.configuration,
            "createdAt": self.created_at.isoformat(),
            "updatedAt": self.updated_at.isoformat() if self.updated_at else None,
        }
