"""
berita_acara.py — SQLAlchemy model untuk Berita Acara Sidang.

Menyimpan hasil pemrosesan GPT dari transkripsi: pasangan tanya-jawab
dalam format JSON terenkripsi, beserta prompt yang digunakan admin.
"""

from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime, timezone

from app.core.database import Base


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


class BeritaAcara(Base):
    __tablename__ = "berita_acara"

    id              = Column(Integer, primary_key=True, index=True)

    # Relasi ke task transkripsi sumber
    task_id         = Column(
        Integer,
        ForeignKey("transkripsi_tasks.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    # Relasi ke user yang membuat
    user_id         = Column(
        Integer,
        ForeignKey("users.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )

    # Judul dokumen (opsional, bisa diedit user)
    title           = Column(String, nullable=True, default="Berita Acara Sidang")

    # Hasil GPT: JSON array terenkripsi (Fernet)
    # Format plaintext: [{"id": 1, "question": "...", "answer": "..."}, ...]
    qa_json_encrypted = Column(Text, nullable=True)

    # Prompt yang dipakai (snapshot saat pembuatan)
    prompt_used     = Column(Text, nullable=True)

    # Status pemrosesan
    status          = Column(String, default="pending")  # pending | processing | completed | failed
    error_message   = Column(Text, nullable=True)

    # Metadata
    model_used      = Column(String, nullable=True, default="gpt-4o-mini")
    processing_time = Column(String, nullable=True)

    # Jumlah biaya yang dibebankan saat pembuatan BA (untuk keperluan refund jika gagal)
    billed_amount   = Column(Integer, nullable=True)

    created_at      = Column(DateTime(timezone=True), default=_utcnow)
    updated_at      = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)

    # Relasi
    task            = relationship("TranskripsiTask", backref="berita_acara", lazy="select")
    owner           = relationship("User", backref="berita_acara", lazy="select")


class BeritaAcaraPrompt(Base):
    """
    Tabel konfigurasi prompt GPT untuk Berita Acara.
    Hanya ada satu baris (singleton config), admin bisa update via panel.
    """
    __tablename__ = "berita_acara_prompts"

    id              = Column(Integer, primary_key=True, index=True)
    name            = Column(String, default="default", unique=True)
    prompt_text     = Column(Text, nullable=False)
    is_active       = Column(Boolean, default=True)
    updated_by      = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    created_at      = Column(DateTime(timezone=True), default=_utcnow)
    updated_at      = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)

    updater         = relationship("User", foreign_keys=[updated_by], lazy="select")