import uuid
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _


class Bengkel(models.Model):
    JENIS_CHOICES = [
        ('Bengkel', _('Bengkel (Workshop)')),
        ('Persidangan', _('Persidangan (Conference)')),
        ('Simposium', _('Simposium')),
        ('Townhall', _('Sesi Libat Urus (Townhall)')),
        ('Latihan', _('Latihan / Kursus')),
        ('Mesyuarat', _('Mesyuarat Strategik')),
        ('Lain-lain', _('Lain-lain')),
    ]
    PRIVASI_CHOICES = [
        ('Tertutup', _('Tertutup (Jemputan Sahaja)')),
        ('Terbuka', _('Terbuka (Iklan Awam & Boleh Dipohon)')),
    ]

    title             = models.CharField(max_length=255)
    jenis_acara       = models.CharField(max_length=50, choices=JENIS_CHOICES, default='Bengkel')
    privasi           = models.CharField(max_length=20, choices=PRIVASI_CHOICES, default='Tertutup')
    description       = models.TextField(blank=True)
    tarikh            = models.DateTimeField()
    tarikh_tamat      = models.DateTimeField(null=True, blank=True)
    lokasi_nama       = models.CharField(max_length=300)
    lokasi_alamat     = models.TextField(blank=True)
    organizer_nama    = models.CharField(max_length=200)
    organizer_email   = models.EmailField(blank=True)
    organizer_telefon = models.CharField(max_length=30, blank=True)
    video_ucapan_url  = models.URLField(blank=True)   # alu-aluan / welcome speech
    video_arah_url    = models.URLField(blank=True)   # directions to hall
    had_peserta       = models.PositiveIntegerField(default=0)  # 0 = no limit
    # --- TAMBAHAN BARU: KAPASITI MEJA ---
    kapasiti_semeja   = models.PositiveIntegerField(default=10, help_text="Jumlah kerusi untuk satu meja (Tetapan Pelan Lantai)")
    # Open registration link (one link, many people)
    reg_token         = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    reg_enabled       = models.BooleanField(default=False)
    
    # Master QR Check-In link (one link, scanned by many attendees)
    master_qr_token   = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    reg_had           = models.PositiveIntegerField(default=0)  # 0 = no extra cap
    # --- TAMBAHAN BARU: KAWALAN KUNCI SPAF ---
    spaf_current_step = models.PositiveIntegerField(default=1, help_text="Tahap Modul SPAF yang sedang dibuka (1-6)")
    # --- TAMBAHAN BARU: KAWALAN KUNCI MAKRO BLUEPRINT ---
    blueprint_current_step = models.PositiveIntegerField(default=1, help_text="Tahap Modul Utama Blueprint yang sedang dibuka (1-8)")
    # --- TAMBAHAN BARU: PEMBEKUAN DATA (DATA FREEZING) ---
    is_locked         = models.BooleanField(default=False, help_text="Jika True, peserta tidak boleh lagi menyumbang idea.")
    created_by        = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, related_name="bengkel_dicipta"
    )
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        ordering         = ["-tarikh"]
        verbose_name     = _("Bengkel")
        verbose_name_plural = _("Senarai Bengkel")

    def __str__(self):
        return self.title

    @property
    def status_display(self):
        """Return 'akan_datang', 'berlangsung', atau 'selesai'."""
        from django.utils import timezone
        now = timezone.now()
        if self.tarikh > now:
            return 'akan_datang'
        if self.tarikh_tamat and self.tarikh_tamat >= now:
            return 'berlangsung'
        return 'selesai'

    @property
    def is_active(self):
        return self.status_display != 'selesai'

    @property
    def jumlah_jemputan(self):
        return self.jemputan.count()

    @property
    def jumlah_diterima(self):
        return self.jemputan.filter(status="accepted").count()

    @property
    def jumlah_ditolak(self):
        return self.jemputan.filter(status="rejected").count()

    @property
    def jumlah_menunggu(self):
        return self.jemputan.filter(status="pending").count()

    @property
    def jumlah_hadir(self):
        return Kehadiran.objects.filter(jemputan__bengkel=self).count()

    def _youtube_embed(self, url):
        """Convert YouTube watch/short URL to embed URL."""
        if not url:
            return url
        if "youtube.com/watch?v=" in url:
            vid = url.split("watch?v=")[1].split("&")[0]
            return f"https://www.youtube.com/embed/{vid}"
        if "youtu.be/" in url:
            vid = url.split("youtu.be/")[1].split("?")[0]
            return f"https://www.youtube.com/embed/{vid}"
        return url

    @property
    def video_ucapan_embed(self):
        return self._youtube_embed(self.video_ucapan_url)

    @property
    def video_arah_embed(self):
        return self._youtube_embed(self.video_arah_url)


class Jemputan(models.Model):
    STATUS_CHOICES = [
        ("pending",  "Menunggu"),
        ("accepted", "Diterima"),
        ("rejected", "Ditolak"),
    ]

    bengkel          = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="jemputan")
    nama             = models.CharField(max_length=200, blank=True)
    email            = models.EmailField(blank=True)
    username         = models.CharField(max_length=100, blank=True)
    organisasi       = models.CharField(max_length=200, blank=True)
    jawatan          = models.CharField(max_length=200, blank=True)
    unit             = models.CharField(max_length=200, blank=True)
    alamat           = models.TextField(blank=True)
    # Linked user account (auto-linked when user logs in with same email)
    user             = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True, related_name="jemputan"
    )
    # Unique tokens
    token            = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    qr_token         = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    # State
    status           = models.CharField(max_length=20, choices=STATUS_CHOICES, default="pending")
    dijemput_oleh    = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True, related_name="jemputan_dihantar"
    )
    responded_at     = models.DateTimeField(null=True, blank=True)
    catatan_invitee  = models.TextField(blank=True)
    created_at       = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering            = ["-created_at"]
        verbose_name        = _("Jemputan")
        verbose_name_plural = _("Senarai Jemputan")
    def __str__(self):
        return f"{self.nama} — {self.bengkel.title}"

    @property
    def sudah_hadir(self):
        return hasattr(self, "kehadiran")


class Kehadiran(models.Model):
    jemputan       = models.OneToOneField(Jemputan, on_delete=models.CASCADE, related_name="kehadiran")
    checked_in_at  = models.DateTimeField(auto_now_add=True)
    checked_in_by  = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True, related_name="check_ins"
    )

    class Meta:
        verbose_name        = "Kehadiran"
        verbose_name_plural = "Rekod Kehadiran"

    def __str__(self):
        return f"{self.jemputan.nama} — {self.checked_in_at:%d/%m/%Y %H:%M}"


class UserProfile(models.Model):
    user        = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
    telefon     = models.CharField(max_length=30, blank=True)
    jabatan     = models.CharField(max_length=200, blank=True)
    organisasi  = models.CharField(max_length=200, blank=True)
    unit        = models.CharField(max_length=200, blank=True)
    alamat      = models.TextField(blank=True)
    
    # --- TAMBAHAN BARU: PEMPROFILAN KOGNITIF AI ---
    persona_ai         = models.CharField(max_length=100, blank=True, null=True, help_text="Cth: Pelaksana, Pemikir Strategik")
    huraian_kognitif   = models.TextField(blank=True, null=True, help_text="Huraian panjang dari AI")
    radar_data_json    = models.JSONField(blank=True, null=True, help_text="Data senarai nilai untuk graf Radar")
    ai_generated_at    = models.DateTimeField(null=True, blank=True, help_text="Bila kali terakhir AI menjana profil ini")
    
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = "Profil Pengguna"
        verbose_name_plural = "Profil Pengguna"

    def __str__(self):
        return f"Profil {self.user.username}"


class PenganjurRequest(models.Model):
    STATUS_CHOICES = [
        ("pending",  "Menunggu Semakan"),
        ("approved", "Diluluskan"),
        ("rejected", "Ditolak"),
    ]

    user            = models.OneToOneField(User, on_delete=models.CASCADE, related_name="penganjur_request")
    status          = models.CharField(max_length=20, choices=STATUS_CHOICES, default="pending")
    sebab           = models.TextField(blank=True, help_text="Sebab permohonan (ditulis oleh pemohon)")
    catatan_admin   = models.TextField(blank=True, help_text="Catatan semakan admin")
    temp_password   = models.CharField(max_length=50, blank=True, help_text="Paparan kata laluan sementara untuk rujukan admin") # TAMBAHAN BARU
    created_at      = models.DateTimeField(auto_now_add=True)
    updated_at      = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = _("Permohonan Penganjur")
        verbose_name_plural = _("Permohonan Penganjur")
        ordering            = ["-created_at"]

    def __str__(self):
        return f"{self.user.username} — {self.get_status_display()}"


# ── Contribution (file upload + comment) ─────────────────────────────────────

class BengkelContribution(models.Model):
    bengkel      = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="contributions")
    jemputan     = models.OneToOneField(Jemputan, on_delete=models.CASCADE, related_name="contribution")
    comment      = models.TextField(blank=True)
    submitted_at = models.DateTimeField(auto_now_add=True)
    updated_at   = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = _("Sumbangan Peserta")
        verbose_name_plural = _("Sumbangan Peserta")
        ordering            = ["submitted_at"]

    def __str__(self):
        return f"{self.jemputan.nama} — {self.bengkel.title}"


class ContributionFile(models.Model):
    contribution  = models.ForeignKey(BengkelContribution, on_delete=models.CASCADE, related_name="files")
    file          = models.FileField(upload_to="contributions/%Y/%m/")
    original_name = models.CharField(max_length=255)
    summary       = models.TextField(blank=True)   # per-file comment/summary
    
    # --- IDEA 2: ANTI-PLAGIAT (Kriptografi Hash) ---
    fail_hash     = models.CharField(max_length=64, blank=True, null=True, db_index=True, help_text="Cop jari digital (SHA-256) fail")
    is_duplicate  = models.BooleanField(default=False, help_text="Ditanda True jika fail diciplak dari peserta lain")
    
    # --- TAMBAHAN BARU: SIMPANAN TEKS UNTUK HIBRID CELERY ---
    teks_diekstrak = models.TextField(blank=True, null=True, help_text="Teks penuh dokumen yang diekstrak semasa muat naik.")
    uploaded_at   = models.DateTimeField(auto_now_add=True)

    # --- RUANGAN ANALITIK AI BARU ---
    skor_novelty = models.FloatField(default=0.0) # Skor 1-10
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor 0-10. Fail markah 0 adalah fail sampah/tidak relevan") # --- IDEA 1: ANTI-SAMPAH ---
    indeks_kebolehtindakan = models.IntegerField(default=0) # Peratus 0-100
    nada_dokumen = models.CharField(max_length=50, blank=True, null=True) # Positif, Negatif, Neutral
    tema_utama = models.CharField(max_length=255, blank=True, null=True) # Contoh: Kewangan, Tadbir Urus
    kompleksiti_kognitif = models.CharField(max_length=100, blank=True, null=True) # Sistematik, Linear, dll
    
    # Ringkasan analitik penuh dari AI (dalam format JSON)
    analitik_data = models.JSONField(blank=True, null=True) 

    class Meta:
        ordering = ["uploaded_at"]

    def __str__(self):
        return self.original_name


# ── LLM-generated laporan (PDF per domain) ───────────────────────────────────

class TentativeBengkel(models.Model):
    bengkel    = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="tentative")
    masa       = models.CharField(max_length=50, help_text="Contoh: 08:00 - 09:00")
    aktiviti   = models.CharField(max_length=300)
    penerangan = models.TextField(blank=True)
    urutan     = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name        = _("Tentative")
        verbose_name_plural = _("Tentative Bengkel")
        ordering            = ["urutan", "created_at"]

    def __str__(self):
        return f"{self.masa} — {self.aktiviti}"


class BengkelLaporan(models.Model):
    STATUS_CHOICES = [
        ("pending",    "Menunggu"),
        ("processing", "Sedang Diproses"),
        ("done",       "Selesai"),
        ("failed",     "Gagal"),
    ]

    bengkel      = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="laporan")
    tajuk        = models.CharField(max_length=300)
    pdf_file     = models.FileField(upload_to="laporan/%Y/%m/", blank=True)
    status       = models.CharField(max_length=20, choices=STATUS_CHOICES, default="pending")
    ralat        = models.TextField(blank=True)
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering            = ["generated_at"]
        verbose_name        = "Laporan Bengkel"
        verbose_name_plural = "Laporan Bengkel"

    def __str__(self):
        return f"{self.bengkel.title} — {self.tajuk}"


# ── Situational Analysis Tools ───────────────────────────────────────────────

class AnalisisSWOT(models.Model):
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="swot_set", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="swot_set")
    kekuatan    = models.TextField(verbose_name="Kekuatan (Strengths)")
    kelemahan   = models.TextField(verbose_name="Kelemahan (Weaknesses)")
    peluang     = models.TextField(verbose_name="Peluang (Opportunities)")
    ancaman     = models.TextField(verbose_name="Ancaman (Threats)")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = "Analisis SWOT"
        verbose_name_plural = "Analisis SWOT"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"SWOT — {self.user.get_full_name() or self.user.username} ({self.created_at:%d/%m/%Y})"


class AnalisisPESTEL(models.Model):
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="pestel_set", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="pestel_set")
    politik     = models.TextField(verbose_name="Faktor Politik (Political)")
    ekonomi     = models.TextField(verbose_name="Faktor Ekonomi (Economic)")
    sosial      = models.TextField(verbose_name="Faktor Sosial (Social)")
    teknologi   = models.TextField(verbose_name="Faktor Teknologi (Technological)")
    alam_sekitar = models.TextField(verbose_name="Faktor Alam Sekitar (Environmental)")
    undang_undang = models.TextField(verbose_name="Faktor Undang-Undang (Legal)")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = "Analisis PESTEL"
        verbose_name_plural = "Analisis PESTEL"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"PESTEL — {self.user.get_full_name() or self.user.username} ({self.created_at:%d/%m/%Y})"


class AnalisisVMOST(models.Model):
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="vmost_set", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="vmost_set")
    visi        = models.TextField(verbose_name="Visi (Vision)")
    misi        = models.TextField(verbose_name="Misi (Mission)")
    objektif    = models.TextField(verbose_name="Objektif (Objectives)")
    strategi    = models.TextField(verbose_name="Strategi (Strategy)")
    taktik      = models.TextField(verbose_name="Taktik (Tactics)")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = "Analisis VMOST"
        verbose_name_plural = "Analisis VMOST"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"VMOST — {self.user.get_full_name() or self.user.username} ({self.created_at:%d/%m/%Y})"


class Analisis5C(models.Model):
    bengkel         = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="fivec_set", null=True, blank=True)
    user            = models.ForeignKey(User, on_delete=models.CASCADE, related_name="fivec_set")
    syarikat        = models.TextField(verbose_name="Syarikat/Organisasi (Company)")
    pelanggan       = models.TextField(verbose_name="Pelanggan (Customers)")
    pesaing         = models.TextField(verbose_name="Pesaing (Competitors)")
    rakan_kongsi    = models.TextField(verbose_name="Rakan Kongsi (Collaborators)")
    persekitaran    = models.TextField(verbose_name="Persekitaran (Climate)")
    catatan         = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    skor_relevansi  = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    created_at      = models.DateTimeField(auto_now_add=True)
    updated_at      = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = "Analisis 5C"
        verbose_name_plural = "Analisis 5C"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"5C — {self.user.get_full_name() or self.user.username} ({self.created_at:%d/%m/%Y})"


class AnalisisSOAR(models.Model):
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="soar_set", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="soar_set")
    kekuatan    = models.TextField(verbose_name="Kekuatan (Strengths)")
    peluang     = models.TextField(verbose_name="Peluang (Opportunities)")
    aspirasi    = models.TextField(verbose_name="Aspirasi (Aspirations)")
    keputusan   = models.TextField(verbose_name="Keputusan/Hasil (Results)")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name        = "Analisis SOAR"
        verbose_name_plural = "Analisis SOAR"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"SOAR — {self.user.get_full_name() or self.user.username} ({self.created_at:%d/%m/%Y})"


# ── SPAF — Situational Problem Analysis Framework ────────────────────────────

class SpafPainPoint(models.Model):
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="spaf_pain_points", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="spaf_pain_points")
    tajuk       = models.TextField(verbose_name="Tajuk / Nama Masalah")
    keterangan  = models.TextField(verbose_name="Huraian Masalah")
    kesan       = models.TextField(verbose_name="Kesan / Impak yang Dirasai")
    keutamaan   = models.CharField(
        max_length=20,
        choices=[("tinggi", "Tinggi"), ("sederhana", "Sederhana"), ("rendah", "Rendah")],
        default="sederhana",
    )
    # --- RUANGAN ANALITIK AI BARU (GAMIFIKASI) ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor 0-10. 0 bermaksud aduan sampah/tidak relevan.")
    is_processed_by_ai = models.BooleanField(default=False, help_text="Penanda AI sudah menilai aduan ini.")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name        = "SPAF — Pain Point"
        verbose_name_plural = "SPAF — Pain Point"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"PainPoint — {self.user.username} ({self.created_at:%d/%m/%Y})"


class SpafProblemStatement(models.Model):
    bengkel       = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="spaf_problem_statements", null=True, blank=True)
    user          = models.ForeignKey(User, on_delete=models.CASCADE, related_name="spaf_problem_statements")
    masalah_utama = models.TextField(verbose_name="Pernyataan Masalah Utama")
    skop          = models.TextField(verbose_name="Skop & Batasan")
    sasaran       = models.TextField(verbose_name="Pihak yang Terjejas")
    matlamat      = models.TextField(verbose_name="Matlamat Penyelesaian")
    catatan       = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    
    # --- RUANGAN ANALITIK PEMBAIKAN (MINI DASHBOARD) ---
    jumlah_refine = models.PositiveIntegerField(default=0, help_text="Berapa ramai peserta yang memberi komen")
    kata_kunci_refine = models.CharField(max_length=255, blank=True, null=True, help_text="Kata kunci rumusan AI")
    
    created_at    = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name        = "SPAF — Problem Statement"
        verbose_name_plural = "SPAF — Problem Statement"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"ProbStatement — {self.user.username} ({self.created_at:%d/%m/%Y})"


class SpafRootCauseAnalysis(models.Model):
    bengkel          = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="spaf_rca", null=True, blank=True)
    user             = models.ForeignKey(User, on_delete=models.CASCADE, related_name="spaf_rca")
    masalah          = models.TextField(verbose_name="Masalah yang Dianalisis")
    punca_utama      = models.TextField(verbose_name="Punca Akar (Root Cause)")
    punca_penyumbang = models.TextField(verbose_name="Faktor Penyumbang")
    bukti            = models.TextField(verbose_name="Bukti / Data Sokongan")
    catatan          = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi   = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at       = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name        = "SPAF — Root Cause Analysis"
        verbose_name_plural = "SPAF — Root Cause Analysis"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"RCA — {self.user.username} ({self.created_at:%d/%m/%Y})"


class SpafRootCauseValidation(models.Model):
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="spaf_rcv", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="spaf_rcv")
    punca       = models.TextField(verbose_name="Punca yang Disahkan")
    kaedah      = models.TextField(verbose_name="Kaedah Pengesahan")
    dapatan     = models.TextField(verbose_name="Dapatan Pengesahan")
    kesimpulan  = models.TextField(verbose_name="Kesimpulan")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name        = "SPAF — Root Cause Validation"
        verbose_name_plural = "SPAF — Root Cause Validation"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"RCV — {self.user.username} ({self.created_at:%d/%m/%Y})"


class SpafRiskAnalysis(models.Model):
    LEVEL = [("tinggi", "Tinggi"), ("sederhana", "Sederhana"), ("rendah", "Rendah")]
    bengkel     = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="spaf_risks", null=True, blank=True)
    user        = models.ForeignKey(User, on_delete=models.CASCADE, related_name="spaf_risks")
    risiko      = models.TextField(verbose_name="Kenyataan Risiko")
    kemungkinan = models.CharField(max_length=20, choices=LEVEL, default="sederhana")
    impak       = models.CharField(max_length=20, choices=LEVEL, default="sederhana")
    mitigasi    = models.TextField(verbose_name="Strategi Mitigasi")
    pemilik     = models.CharField(max_length=200, blank=True, verbose_name="Pemilik Risiko")
    catatan     = models.TextField(blank=True, verbose_name="Catatan Tambahan")
    
    # --- RUANGAN ANALITIK AI BARU (GAMIFIKASI) ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor 0-10. 0 bermaksud aduan sampah/tidak relevan.")
    is_processed_by_ai = models.BooleanField(default=False, help_text="Penanda AI sudah menilai aduan ini.")
    
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name        = "SPAF — Risk Analysis"
        verbose_name_plural = "SPAF — Risk Analysis"
        ordering            = ["-created_at"]

    def __str__(self):
        return f"Risk — {self.user.username} ({self.created_at:%d/%m/%Y})"


# ── Blueprint — Themes (Step 3 synthesis) ────────────────────────────────────

class BlueprintTheme(models.Model):
    bengkel      = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="blueprint_themes")
    urutan       = models.PositiveIntegerField(default=0)
    tema         = models.CharField(max_length=300)
    penerangan   = models.TextField()
    kata_kunci   = models.TextField(blank=True)
    frequency    = models.PositiveIntegerField(default=1)
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering            = ["urutan", "id"]
        verbose_name        = "Blueprint — Tema"
        verbose_name_plural = "Blueprint — Tema"

    def __str__(self):
        return f"Tema: {self.tema} [{self.bengkel.title}]"

    # --- TAMBAH KOD INI ---
    @property
    def senarai_kata_kunci(self):
        """Pecahkan string kata kunci kepada list secara automatik"""
        if self.kata_kunci:
            return [k.strip() for k in self.kata_kunci.split(",") if k.strip()]
        return []
    
# ── Blueprint — Tema Undian & Cadangan (Jejak DNA) ────────────────────────────

class ThemeVote(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="theme_votes")
    tema = models.ForeignKey(BlueprintTheme, on_delete=models.CASCADE, related_name="votes")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # Memastikan seorang peserta hanya boleh undi tema yang sama SEKALI sahaja
        unique_together = ('user', 'tema')
        verbose_name = "Blueprint — Undian Tema"
        verbose_name_plural = "Blueprint — Undian Tema"

    def __str__(self):
        return f"{self.user.username} mengundi {self.tema.tema}"


class ThemeIdea(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="theme_ideas")
    tema = models.ForeignKey(BlueprintTheme, on_delete=models.CASCADE, related_name="ideas")
    idea = models.TextField(verbose_name="Cadangan Penambahbaikan")
    # Status ini berguna untuk AI tahu sama ada idea ini sudah diproses ke fasa Teras atau belum
    status_ai = models.CharField(max_length=20, default="pending") 
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Blueprint — Idea Tema"
        verbose_name_plural = "Blueprint — Idea Tema"
        ordering = ["-created_at"]

    def __str__(self):
        return f"Idea dari {self.user.username} untuk {self.tema.tema[:20]}..."
    
# ── Blueprint — Teras Strategik & Sokongan (Langkah 4) ───────────────────────

class BlueprintPillar(models.Model):
    bengkel      = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="blueprint_pillars")
    urutan       = models.PositiveIntegerField(default=0)
    teras        = models.CharField(max_length=300, verbose_name="Nama Teras")
    penerangan   = models.TextField()
    # Untuk menyimpan rekod tema apa yang telah disatukan oleh AI ke dalam Teras ini
    tema_dirangkumi = models.TextField(blank=True, help_text="Senarai Tema yang membentuk Teras ini")
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering            = ["urutan", "id"]
        verbose_name        = "Blueprint — Teras"
        verbose_name_plural = "Blueprint — Teras"

    def __str__(self):
        return f"Teras: {self.teras} [{self.bengkel.title}]"


class PillarVote(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="pillar_votes")
    pillar = models.ForeignKey(BlueprintPillar, on_delete=models.CASCADE, related_name="votes")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # Memastikan seorang peserta hanya boleh sokong teras yang sama SEKALI sahaja
        unique_together = ('user', 'pillar')
        verbose_name = "Blueprint — Sokongan Teras"
        verbose_name_plural = "Blueprint — Sokongan Teras"

    def __str__(self):
        return f"{self.user.username} menyokong {self.pillar.teras}"


class PillarIdea(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="pillar_ideas")
    pillar = models.ForeignKey(BlueprintPillar, on_delete=models.CASCADE, related_name="ideas")
    idea = models.TextField(verbose_name="Cadangan Skop Teras")
    status_ai = models.CharField(max_length=20, default="pending") 
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Blueprint — Skop Teras"
        verbose_name_plural = "Blueprint — Skop Teras"
        ordering = ["-created_at"]

    def __str__(self):
        return f"Skop dari {self.user.username} untuk {self.pillar.teras[:20]}..."

# ── Blueprint — Strategi Berfasa (Langkah 5) ─────────────────────────────────

class BlueprintStrategy(models.Model):
    bengkel = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="blueprint_strategies")
    urutan = models.PositiveIntegerField(default=0, help_text="1 hingga 6 (Mewakili 6 Fasa)")
    fasa = models.CharField(max_length=50, verbose_name="Label Fasa", help_text="Contoh: FASA 1 (2026-2030)")
    tajuk = models.CharField(max_length=300, verbose_name="Fokus Utama Fasa")
    penerangan = models.TextField()
    teras_berkaitan = models.TextField(blank=True, help_text="Teras mana yang disentuh dalam fasa ini")
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["urutan"]
        verbose_name = "Blueprint — Strategi"
        verbose_name_plural = "Blueprint — Strategi"

    def __str__(self):
        return f"{self.fasa}: {self.tajuk} [{self.bengkel.title}]"


class StrategyIdea(models.Model):
    """
    Peserta tidak mengundi fasa (kerana masa adalah tetap), 
    tetapi mereka menyuntik IDEA INISIATIF/PROJEK untuk fasa tersebut.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="strategy_ideas")
    strategi = models.ForeignKey(BlueprintStrategy, on_delete=models.CASCADE, related_name="ideas")
    idea = models.TextField(verbose_name="Cadangan Inisiatif Projek")
    status_ai = models.CharField(max_length=20, default="pending") 
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Blueprint — Idea Strategi"
        verbose_name_plural = "Blueprint — Idea Strategi"
        ordering = ["-created_at"]

    def __str__(self):
        return f"Projek dari {self.user.username} untuk {self.strategi.fasa}"

# ── Blueprint — Pelan Tindakan Berfasa (Langkah 6) ───────────────────────────

class BlueprintActionPlan(models.Model):
    bengkel = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="blueprint_action_plans")
    # Dipautkan terus ke jadual Strategi (Fasa) supaya AI tahu tindakan ini untuk fasa mana
    strategi = models.ForeignKey(BlueprintStrategy, on_delete=models.CASCADE, related_name="action_plans")
    tajuk = models.CharField(max_length=300, verbose_name="Item Tindakan")
    penerangan = models.TextField(verbose_name="Perincian Pelaksanaan")
    tahun_pelaksanaan = models.CharField(max_length=100, blank=True, null=True, help_text="Contoh: Tahun 1 (2026)")
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # Susun mengikut urutan fasa, kemudian id tindakan
        ordering = ["strategi__urutan", "id"]
        verbose_name = "Blueprint — Pelan Tindakan"
        verbose_name_plural = "Blueprint — Pelan Tindakan"

    def __str__(self):
        return f"Tindakan: {self.tajuk} [{self.strategi.fasa}]"


class ActionPlanIdea(models.Model):
    """
    Di fasa ini, peserta akan diminta menyumbangkan idea KPI (Key Performance Indicator)
    atau cara untuk mengukur kejayaan bagi item tindakan tersebut.
    Ini akan menjadi input (DNA) untuk Langkah 7: Indikator!
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="action_plan_ideas")
    action_plan = models.ForeignKey(BlueprintActionPlan, on_delete=models.CASCADE, related_name="ideas")
    idea = models.TextField(verbose_name="Cadangan KPI / Indikator Kejayaan")
    status_ai = models.CharField(max_length=20, default="pending")
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Blueprint — Idea KPI Tindakan"
        verbose_name_plural = "Blueprint — Idea KPI Tindakan"
        ordering = ["-created_at"]

    def __str__(self):
        return f"KPI dari {self.user.username} untuk {self.action_plan.tajuk[:20]}..."
    
# ── Blueprint — Indikator & Pengukuran (Langkah 7) ───────────────────────────

class BlueprintIndicator(models.Model):
    bengkel = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="blueprint_indicators")
    # KPI ini mengukur Pelan Tindakan yang mana? Kita pautkan ia ke BlueprintActionPlan
    action_plan = models.ForeignKey(BlueprintActionPlan, on_delete=models.CASCADE, related_name="indicators")
    kpi_tajuk = models.CharField(max_length=300, verbose_name="Nama KPI / Indikator")
    sasaran = models.CharField(max_length=200, verbose_name="Sasaran Kejayaan (Target)")
    kekerapan_ukuran = models.CharField(max_length=100, default="Tahunan", help_text="Suku Tahun, Tahunan, dsb.")
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["action_plan__strategi__urutan", "id"]
        verbose_name = "Blueprint — Indikator KPI"
        verbose_name_plural = "Blueprint — Indikator KPI"

    def __str__(self):
        return f"KPI: {self.kpi_tajuk} untuk {self.action_plan.tajuk[:20]}..."

class BlueprintIndicatorCalibration(models.Model):
    """Jadual untuk menyimpan Kalibrasi/Reality Check dari SME"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="kpi_calibrations")
    kpi = models.ForeignKey(BlueprintIndicator, on_delete=models.CASCADE, related_name="calibrations")
    penilaian = models.CharField(max_length=50, help_text="ideal, ambitious, low")
    cadangan_sasaran = models.TextField(blank=True, verbose_name="Cadangan Sasaran Baharu")
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Blueprint — Kalibrasi KPI"
        verbose_name_plural = "Blueprint — Kalibrasi KPI"
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.user.username} nilai KPI {self.kpi.id}: {self.penilaian}"
    
# ── Blueprint — Peruntukan Sumber & Bajet (Langkah 8) ───────────────────────────

class BlueprintAllocation(models.Model):
    bengkel = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name="blueprint_allocations")
    # Sumber ini diperuntukkan untuk melaksanakan Tindakan yang mana?
    action_plan = models.ForeignKey(BlueprintActionPlan, on_delete=models.CASCADE, related_name="allocations")
    kategori_sumber = models.CharField(max_length=100, help_text="Contoh: Kewangan, Manusia, Fasiliti, Teknologi")
    anggaran_keperluan = models.CharField(max_length=300, verbose_name="Anggaran/Fokus Keperluan")
    justifikasi = models.TextField(blank=True, verbose_name="Sebab Keperluan")
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["action_plan__strategi__urutan", "kategori_sumber"]
        verbose_name = "Blueprint — Peruntukan Sumber"
        verbose_name_plural = "Blueprint — Peruntukan Sumber"

    def __str__(self):
        return f"{self.kategori_sumber} untuk {self.action_plan.tajuk[:20]}..."


class AllocationIdea(models.Model):
    """
    Peserta akan menyumbangkan idea tentang apa sumber spesifik 
    (cth: "Perlu dana RM500k untuk server", "Perlu 5 pakar data") yang diperlukan.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="allocation_ideas")
    action_plan = models.ForeignKey(BlueprintActionPlan, on_delete=models.CASCADE, related_name="allocation_ideas")
    idea_sumber = models.TextField(verbose_name="Cadangan Keperluan Sumber")
    
    # --- TAMBAHAN BARU: SIMPAN SKOR AI ---
    skor_relevansi = models.FloatField(default=0.0, help_text="Skor kualiti AI untuk Gamifikasi")
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Blueprint — Idea Peruntukan"
        verbose_name_plural = "Blueprint — Idea Peruntukan"
        ordering = ["-created_at"]

    def __str__(self):
        return f"Sumber dari {self.user.username} untuk {self.action_plan.tajuk[:20]}..."
    
# ==============================================================================
# FORUM & PERBINCANGAN LOBI BENGKEL
# ==============================================================================

class ForumThread(models.Model):
    bengkel = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name='forum_threads')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    kandungan = models.TextField(help_text="Kandungan topik / persoalan")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user.username} - {self.bengkel.title}"

class ForumReply(models.Model):
    thread = models.ForeignKey(ForumThread, on_delete=models.CASCADE, related_name='replies')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    kandungan = models.TextField(help_text="Balasan kepada thread")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Reply by {self.user.username} on {self.thread.id}"

# ==============================================================================
# MAKLUM BALAS & PENILAIAN PENGANJUR (360-DEGREE FEEDBACK)
# ==============================================================================

class MaklumBalasPenganjur(models.Model):
    bengkel = models.ForeignKey(Bengkel, on_delete=models.CASCADE, related_name='maklum_balas')
    # Siapa yang memberi rating
    peserta = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rating_diberikan')
    # Siapa yang menerima rating (Penganjur)
    penganjur = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rating_diterima')
    
    # Skala 1 hingga 5 bintang
    rating = models.PositiveSmallIntegerField(default=5)
    komen = models.TextField(blank=True, help_text="Ulasan bertulis peserta terhadap pengurusan acara")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # Memastikan seorang peserta hanya boleh menilai satu acara sekali sahaja
        unique_together = ('bengkel', 'peserta')
        verbose_name = "Maklum Balas Penganjur"
        verbose_name_plural = "Maklum Balas Penganjur"
        ordering = ["-created_at"]

    def __str__(self):
        return f"Rating {self.rating}/5 oleh {self.peserta.username} untuk {self.bengkel.title}"
    
