"""SQLAlchemy models for the AI RPG backend.""" from __future__ import annotations from datetime import datetime, timezone from typing import Any, Dict, List, Optional import uuid from sqlalchemy import ( Boolean, DateTime, ForeignKey, Integer, String, Text, JSON, func, ) from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.orm import Mapped, mapped_column, relationship from app.db import Base def _utcnow() -> datetime: return datetime.now(timezone.utc) class User(Base): __tablename__ = "users" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False) username: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False) hashed_password: Mapped[str] = mapped_column(String(255), nullable=False) is_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) preferred_language: Mapped[str] = mapped_column(String(8), default="en", nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False) worlds: Mapped[List["World"]] = relationship(back_populates="owner", cascade="all, delete-orphan") class Setting(Base): """Key/value admin settings. Override defaults (LLM, context manager params).""" __tablename__ = "settings" key: Mapped[str] = mapped_column(String(128), primary_key=True) value: Mapped[Any] = mapped_column(JSONB, nullable=False) description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow, nullable=False) class Preset(Base): """World presets published by admin or users.""" __tablename__ = "presets" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) slug: Mapped[str] = mapped_column(String(128), unique=True, index=True, nullable=False) title: Mapped[str] = mapped_column(String(255), nullable=False) description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) language: Mapped[str] = mapped_column(String(8), default="en", nullable=False) is_public: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) is_builtin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) # JSON: world_schema, default_rules, initial_state, world_seed_prompt, suggested_system_prompt payload: Mapped[Dict[str, Any]] = mapped_column(JSONB, nullable=False) author_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False) class World(Base): __tablename__ = "worlds" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False, index=True) name: Mapped[str] = mapped_column(String(255), nullable=False) language: Mapped[str] = mapped_column(String(8), default="en", nullable=False) # Frozen world definition: setting description, rules, world_schema (JSON Schema for state), plot_rails definition: Mapped[Dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) # Current live state of the world (player character, NPC, inventory, time, etc.) state: Mapped[Dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) # Current world time (ISO string) current_time: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) # Status: draft / ready / active / archived status: Mapped[str] = mapped_column(String(32), default="draft", nullable=False, index=True) preset_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("presets.id"), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow, nullable=False) owner: Mapped[User] = relationship(back_populates="worlds") sessions: Mapped[List["Session"]] = relationship(back_populates="world", cascade="all, delete-orphan") class Session(Base): __tablename__ = "sessions" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) world_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("worlds.id"), nullable=False, index=True) title: Mapped[str] = mapped_column(String(255), default="New session", nullable=False) # Snapshot of world state at session start (we mutate world.state during play; session stores narrative history) is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False) last_played_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) world: Mapped[World] = relationship(back_populates="sessions") messages: Mapped[List["Message"]] = relationship( back_populates="session", cascade="all, delete-orphan", order_by="Message.seq" ) triggers: Mapped[List["DeferredTrigger"]] = relationship( back_populates="session", cascade="all, delete-orphan" ) class Message(Base): """Conversation messages: scene steps, player actions, orchestrator thoughts, summaries.""" __tablename__ = "messages" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) session_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("sessions.id"), nullable=False, index=True) seq: Mapped[int] = mapped_column(Integer, nullable=False, index=True) # role: system / user / assistant / scene / summary / technical / tool role: Mapped[str] = mapped_column(String(32), nullable=False) # kind: narrative_step / player_action / orchestrator_plan / tool_call / summary / technical_offscreen / system_note kind: Mapped[str] = mapped_column(String(64), default="narrative_step", nullable=False) content: Mapped[str] = mapped_column(Text, nullable=False, default="") # Structured payload: suggested_options, tool_calls, state_diff, time_diff, etc. payload: Mapped[Dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) # Whether this message is in the "guaranteed recent" context window is_pinned: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) # True if message is hidden from the chat UI (technical, tool, summary) hidden: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False) session: Mapped[Session] = relationship(back_populates="messages") class DeferredTrigger(Base): """Scheduled events tied to in-world time.""" __tablename__ = "deferred_triggers" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) session_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("sessions.id"), nullable=False, index=True) # ISO datetime in world's internal time fire_at: Mapped[str] = mapped_column(String(64), nullable=False, index=True) description: Mapped[str] = mapped_column(Text, nullable=False) # Arbitrary payload (what should happen, who, conditions) payload: Mapped[Dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) fired: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False) session: Mapped[Session] = relationship(back_populates="triggers") class LlmCallLog(Base): """All LLM calls logged for observability and cost tracking.""" __tablename__ = "llm_call_logs" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=True, index=True) session_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("sessions.id"), nullable=True, index=True) purpose: Mapped[str] = mapped_column(String(64), nullable=False) # orchestrator / step / summary / world_builder / subagent model: Mapped[str] = mapped_column(String(255), nullable=False) base_url: Mapped[str] = mapped_column(String(512), nullable=False) prompt_messages: Mapped[List[Dict[str, Any]]] = mapped_column(JSONB, nullable=False, default=list) # tools schema sent tools: Mapped[Optional[List[Dict[str, Any]]]] = mapped_column(JSONB, nullable=True) # response response_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) tool_calls: Mapped[Optional[List[Dict[str, Any]]]] = mapped_column(JSONB, nullable=True) prompt_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) completion_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) total_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) error: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False, index=True) class GlossaryEntry(Base): """Indexed facts for RAG (glossary terms, NPCs, locations, items).""" __tablename__ = "glossary_entries" id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) world_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("worlds.id"), nullable=False, index=True) session_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("sessions.id"), nullable=True, index=True) # kind: npc / location / item / lore / event / rule kind: Mapped[str] = mapped_column(String(32), default="lore", nullable=False) name: Mapped[str] = mapped_column(String(255), nullable=False) description: Mapped[str] = mapped_column(Text, nullable=False, default="") payload: Mapped[Dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False)