from datetime import datetime, timezone
from sqlalchemy import Boolean, Column, DateTime, Index, String, Text
from sqlalchemy.dialects.postgresql import JSONB
from database.postgres import Base


def _now():
    return datetime.now(timezone.utc)


class MelodyDraft(Base):
    __tablename__ = "melody_drafts"
    __table_args__ = (
        Index("idx_melody_drafts_status", "status"),
    )

    id         = Column(String(128), primary_key=True)
    status     = Column(String(32), nullable=False, default="draft")
    # 'data' stores the full melody definition as JSON (was TEXT/JSON in SQLite)
    data       = Column(JSONB, nullable=False)
    created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
    updated_at = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)


class BuiltMelody(Base):
    __tablename__ = "built_melodies"

    id                  = Column(String(128), primary_key=True)
    name                = Column(String(500), nullable=False)
    pid                 = Column(String(128), nullable=False)
    # 'steps' is a JSON array of step definitions
    steps               = Column(JSONB, nullable=False)
    binary_path         = Column(String(1000))
    progmem_code        = Column(Text)
    # JSON array of melody IDs this built melody is assigned to
    assigned_melody_ids = Column(JSONB, nullable=False, default=list)
    is_builtin          = Column(Boolean, nullable=False, default=False)
    created_at          = Column(DateTime(timezone=True), nullable=False, default=_now)
    updated_at          = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
