"""
SQLAlchemy model for concepts table.

Concepts form the backbone of the knowledge graph hierarchy,
with self-referential parent_id for tree structure.
"""

from __future__ import annotations

import uuid

from sqlalchemy import Boolean, Column, DateTime, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

from pycharter.db.models.base import Base


class ConceptModel(Base):
    """SQLAlchemy model for concepts table."""

    __tablename__ = "concepts"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = Column(String(255), nullable=False, unique=True)
    description = Column(Text, nullable=True)
    parent_id = Column(
        UUID(as_uuid=True),
        ForeignKey("pycharter.concepts.id", ondelete="SET NULL"),
        nullable=True,
    )
    tier = Column(String(50), nullable=False, default="free")
    node_kind = Column(String(50), nullable=True)

    uri = Column(String(512), nullable=True)
    notation = Column(String(255), nullable=True)
    deprecated = Column(Boolean, nullable=False, server_default="false")

    # Audit fields
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    created_by = Column(String(255), nullable=True)
    updated_by = Column(String(255), nullable=True)

    # Self-referential relationship
    parent = relationship("ConceptModel", remote_side=[id])

    __table_args__ = ({"schema": "pycharter"},)
