"""
feature_flag.py — SQLAlchemy model untuk Feature Flags (toggle fitur).

Menyimpan daftar fitur yang bisa diaktifkan/nonaktifkan oleh admin
tanpa perlu restart server atau deploy ulang.

Cara pakai di route lain:
    from app.services.feature_flag_service import require_feature

    @router.post("/upload")
    def upload(..., _=Depends(require_feature("upload_file"))):
        ...
"""

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

from app.core.database import Base


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


# ── Daftar fitur default yang di-seed saat startup ───────────────────────────
DEFAULT_FLAGS: list[dict] = [
    {
        "key":         "upload_file",
        "label":       "Upload File Audio",
        "description": "Izinkan pengguna mengunggah file audio untuk ditranskripsi.",
        "icon":        "📁",
    },
    {
        "key":         "rekam_live",
        "label":       "Rekam Audio Live",
        "description": "Izinkan pengguna merekam audio secara langsung (real-time).",
        "icon":        "🎙️",
    },
    {
        "key":         "mode_sidang",
        "label":       "Mode Sidang",
        "description": "Aktifkan opsi mode sidang saat transkripsi (speaker diarization).",
        "icon":        "⚖️",
    },
    {
        "key":         "berita_acara",
        "label":       "Berita Acara Sidang",
        "description": "Izinkan pembuatan Berita Acara dari hasil transkripsi via GPT.",
        "icon":        "📄",
    },
    {
        "key":         "transkripsi_api",
        "label":       "Engine Transkripsi API (OpenAI)",
        "description": "Izinkan penggunaan engine Whisper via OpenAI API (berbayar).",
        "icon":        "🌐",
    },
    {
        "key":         "transkripsi_lokal",
        "label":       "Engine Transkripsi Lokal",
        "description": "Izinkan penggunaan engine Whisper lokal (on-premise).",
        "icon":        "🖥️",
    },
    {
        "key":         "topup_enabled",
        "label":       "Fitur Top-Up Saldo",
        "description": "Izinkan pengguna melakukan top-up saldo via Midtrans.",
        "icon":        "💳",
    },
]


class FeatureFlag(Base):
    """
    Satu baris per fitur. Admin bisa toggle `is_enabled` via panel.
    Cache in-memory ditangani di feature_flag_service.py.
    """
    __tablename__ = "feature_flags"

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

    # Key unik, dipakai sebagai identifier di kode (misal: "upload_file")
    key         = Column(String(64), unique=True, index=True, nullable=False)

    # Label tampilan di panel admin
    label       = Column(String(128), nullable=False)

    # Keterangan singkat fungsi fitur ini
    description = Column(Text, nullable=True)

    # Emoji / ikon untuk UI (opsional)
    icon        = Column(String(8), nullable=True, default="⚙️")

    # Status toggle
    is_enabled  = Column(Boolean, default=True, nullable=False)

    # Siapa admin yang terakhir mengubah
    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")

    def to_dict(self) -> dict:
        return {
            "id":          self.id,
            "key":         self.key,
            "label":       self.label,
            "description": self.description,
            "icon":        self.icon or "⚙️",
            "is_enabled":  self.is_enabled,
            "updated_by":  self.updated_by,
            "updated_at":  self.updated_at.isoformat() if self.updated_at else None,
        }