"""Knowledge Vault ORM models."""

from __future__ import annotations

from datetime import datetime, timezone
from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base


class VaultPath(Base):
    """Registered root folder for note indexing."""

    __tablename__ = "vault_paths"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    path: Mapped[str] = mapped_column(String(2048), nullable=False, unique=True, index=True)
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=lambda: datetime.now(timezone.utc),
    )

    files: Mapped[list["VaultFile"]] = relationship(
        back_populates="vault_path",
        cascade="all, delete-orphan",
    )


class VaultFile(Base):
    """Indexed file metadata under a registered vault path."""

    __tablename__ = "vault_files"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    path: Mapped[str] = mapped_column(String(4096), nullable=False, unique=True, index=True)
    vault_path_id: Mapped[int] = mapped_column(
        ForeignKey("vault_paths.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    mtime: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    size: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    sha256: Mapped[str] = mapped_column(String(64), nullable=False, default="")
    last_indexed_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        default=lambda: datetime.now(timezone.utc),
    )

    vault_path: Mapped["VaultPath"] = relationship(back_populates="files")
    chunks: Mapped[list["VaultChunk"]] = relationship(
        back_populates="file",
        cascade="all, delete-orphan",
    )


class VaultChunk(Base):
    """Text chunk extracted from one file for full-text retrieval."""

    __tablename__ = "vault_chunks"
    __table_args__ = (UniqueConstraint("file_id", "chunk_index", name="uq_vault_chunk_file_index"),)

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    file_id: Mapped[int] = mapped_column(
        ForeignKey("vault_files.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    chunk_index: Mapped[int] = mapped_column(Integer, nullable=False)
    start_char: Mapped[int] = mapped_column(Integer, nullable=False)
    end_char: Mapped[int] = mapped_column(Integer, nullable=False)
    text: Mapped[str] = mapped_column(Text, nullable=False)

    file: Mapped["VaultFile"] = relationship(back_populates="chunks")
