from django import template
from django.db.models import Sum
from bengkel.models import (
    ContributionFile, SpafPainPoint, AnalisisSWOT, AnalisisPESTEL, 
    AnalisisVMOST, Analisis5C, AnalisisSOAR, SpafRootCauseAnalysis, 
    SpafRiskAnalysis, ThemeVote, PillarVote, ThemeIdea, PillarIdea, 
    StrategyIdea, ActionPlanIdea, AllocationIdea, SpafRootCauseValidation
)

register = template.Library()

@register.simple_tag
def kira_skor_peserta(user, bengkel):
    """
    Template Tag ini membaca pangkalan data dan mengira skor keseluruhan
    dengan mengambil kira status Plagiat dan Gred Relevansi AI.
    """
    skor_keseluruhan = 0

    if not user.is_authenticated:
        return 0

    # ---------------------------------------------------------
    # 1. NODE 1 (RUJUKAN): Formula AI (Kalis Sampah & Plagiat)
    # ---------------------------------------------------------
    skor_fail_ai = 0
    # Hanya kira fail TULEN (bukan ciplak)
    fail_tulen = ContributionFile.objects.filter(
        contribution__jemputan__user=user, 
        contribution__bengkel=bengkel,
        is_duplicate=False
    )
    
    fail_dinilai = fail_tulen.exclude(skor_novelty=0.0)
    for f in fail_dinilai:
        pengali_relevansi = (f.skor_relevansi / 10.0) if getattr(f, 'skor_relevansi', 0) else 0
        mata_mentah = (f.skor_novelty * 0.5) + (f.indeks_kebolehtindakan * 0.05)
        skor_fail_ai += int(mata_mentah * pengali_relevansi)
        
    fail_belum_dinilai = fail_tulen.count() - fail_dinilai.count()
    deposit_fail = fail_belum_dinilai * 2 
    
    skor_keseluruhan += (skor_fail_ai + deposit_fail)

    # ---------------------------------------------------------
    # 2. NODE 2 (SPAF): Penilaian Dinamik AI (Kalis Sampah)
    # ---------------------------------------------------------
    skor_spaf = 0
    
    # A. Markah dari Aduan/Pain Points (Max 10 pts per aduan)
    aduan_dinilai = SpafPainPoint.objects.filter(user=user, bengkel=bengkel, is_processed_by_ai=True)
    for a in aduan_dinilai:
        pengali_aduan = (a.skor_relevansi / 10.0) if getattr(a, 'skor_relevansi', 0) else 0
        skor_spaf += int(10 * pengali_aduan)
        
    aduan_belum_dinilai = SpafPainPoint.objects.filter(user=user, bengkel=bengkel, is_processed_by_ai=False).count()
    skor_spaf += (aduan_belum_dinilai * 2)
    
    # B. Markah Dinamik dari Situational Analysis (Max 10 pts per kerangka)
    def kira_situasi(qs):
        total = 0
        for obj in qs:
            skor_ai = getattr(obj, 'skor_relevansi', 0.0)
            mata = int(10 * (skor_ai / 10.0))
            total += max(5, mata) if skor_ai > 0 else 5
        return total

    skor_spaf += kira_situasi(AnalisisSWOT.objects.filter(user=user, bengkel=bengkel))
    skor_spaf += kira_situasi(AnalisisPESTEL.objects.filter(user=user, bengkel=bengkel))
    skor_spaf += kira_situasi(AnalisisVMOST.objects.filter(user=user, bengkel=bengkel))
    skor_spaf += kira_situasi(Analisis5C.objects.filter(user=user, bengkel=bengkel))
    skor_spaf += kira_situasi(AnalisisSOAR.objects.filter(user=user, bengkel=bengkel))

    # C. Markah Dinamik dari RCA (Max 15 pts per RCA)
    rca_list = SpafRootCauseAnalysis.objects.filter(user=user, bengkel=bengkel)
    for rca in rca_list:
        skor_ai_rca = getattr(rca, 'skor_relevansi', 0.0)
        mata_rca = int(15 * (skor_ai_rca / 10.0))
        skor_spaf += max(5, mata_rca) if skor_ai_rca > 0 else 5
        
    # D. Markah Dinamik dari RCA Validation / RCV (Max 10 pts per semakan)
    rcv_list = SpafRootCauseValidation.objects.filter(user=user, bengkel=bengkel)
    for rcv in rcv_list:
        skor_ai_rcv = getattr(rcv, 'skor_relevansi', 0.0)
        mata_rcv = int(10 * (skor_ai_rcv / 10.0))
        skor_spaf += max(3, mata_rcv) if skor_ai_rcv > 0 else 3

    # E. Markah Dinamik dari Penilaian Risiko (Max 15 pts per Risiko)
    risk_list = SpafRiskAnalysis.objects.filter(user=user, bengkel=bengkel)
    for risk in risk_list:
        skor_ai_risk = getattr(risk, 'skor_relevansi', 0.0)
        mata_risk = int(15 * (skor_ai_risk / 10.0))
        skor_spaf += max(5, mata_risk) if skor_ai_risk > 0 else 5
    
    skor_keseluruhan += skor_spaf

    # ---------------------------------------------------------
    # 3. NODE 3 & 4 (UNDIAN TEMA/TERAS): 2 pts per undian
    # ---------------------------------------------------------
    jum_undi_tema = ThemeVote.objects.filter(user=user, tema__bengkel=bengkel).count()
    jum_undi_teras = PillarVote.objects.filter(user=user, pillar__bengkel=bengkel).count()
    
    total_undian = jum_undi_tema + jum_undi_teras
    skor_keseluruhan += (total_undian * 2)

    # ---------------------------------------------------------
    # 4. SUNTIKAN DNA / IDEA (SEMUA MODUL)
    # ---------------------------------------------------------
    # Markah Dinamik dari Idea Tema (Max 10 pts per idea)
    idea_tema_list = ThemeIdea.objects.filter(user=user, tema__bengkel=bengkel)
    for idea in idea_tema_list:
        skor_ai_idea = getattr(idea, 'skor_relevansi', 0.0)
        mata_idea = int(10 * (skor_ai_idea / 10.0))
        skor_keseluruhan += max(3, mata_idea) if skor_ai_idea > 0 else 8

    # Markah Dinamik dari Idea Teras/Pillar (Max 10 pts per idea)
    idea_pillar_list = PillarIdea.objects.filter(user=user, pillar__bengkel=bengkel)
    for idea in idea_pillar_list:
        skor_ai_idea_p = getattr(idea, 'skor_relevansi', 0.0)
        mata_idea_p = int(10 * (skor_ai_idea_p / 10.0))
        skor_keseluruhan += max(3, mata_idea_p) if skor_ai_idea_p > 0 else 8

    # Markah Dinamik dari Idea Strategi (Max 10 pts per idea)
    idea_strategi_list = StrategyIdea.objects.filter(user=user, strategi__bengkel=bengkel)
    for idea in idea_strategi_list:
        skor_ai_idea_s = getattr(idea, 'skor_relevansi', 0.0)
        mata_idea_s = int(10 * (skor_ai_idea_s / 10.0))
        skor_keseluruhan += max(3, mata_idea_s) if skor_ai_idea_s > 0 else 8
        
    # Markah Dinamik dari Idea Action Plan / KPI (Max 10 pts per idea)
    idea_action_list = ActionPlanIdea.objects.filter(user=user, action_plan__strategi__bengkel=bengkel)
    for idea in idea_action_list:
        skor_ai_idea_a = getattr(idea, 'skor_relevansi', 0.0)
        mata_idea_a = int(10 * (skor_ai_idea_a / 10.0))
        skor_keseluruhan += max(3, mata_idea_a) if skor_ai_idea_a > 0 else 8
        
    # Markah Dinamik & Flat dari Kalibrasi KPI (Max 5 pts / Minimum 2 pts)
    from bengkel.models import BlueprintIndicatorCalibration
    kpi_calib_list = BlueprintIndicatorCalibration.objects.filter(user=user, kpi__action_plan__strategi__bengkel=bengkel)
    for calib in kpi_calib_list:
        if calib.penilaian == 'ideal':
            skor_keseluruhan += 2
        else:
            skor_ai_calib = getattr(calib, 'skor_relevansi', 0.0)
            mata_calib = int(5 * (skor_ai_calib / 10.0))
            skor_keseluruhan += max(2, mata_calib) if skor_ai_calib > 0 else 2

    # Markah Dinamik & Flat dari Idea Peruntukan (Allocation Idea)
    alloc_list = AllocationIdea.objects.filter(user=user, action_plan__strategi__bengkel=bengkel)
    for alloc in alloc_list:
        if '[SETUJU]' in alloc.idea_sumber:
            skor_keseluruhan += 2
        else:
            skor_ai_alloc = getattr(alloc, 'skor_relevansi', 0.0)
            mata_alloc = int(5 * (skor_ai_alloc / 10.0))
            skor_keseluruhan += max(2, mata_alloc) if skor_ai_alloc > 0 else 2

    return skor_keseluruhan