"""Mizan_Algorithm v4.0 — Trophy-Based 1-to-1 Ledger.

## Formula (LOCKED)

    max_possible = 48 × 120 days
    gain_per_trophy = 500 / max_possible          (+500 at full completion)
    loss_per_trophy = 1500 / max_possible         (3× gain — severity model)

    Score = clamp(500 + (earned × gain_per) - (missing × loss_per) + health_violations, 0, 1000)

## Behavior

    Perfect 120 days -> 1000 (capped)
    15 days missed    -> ~350 (AT_RISK, severity visible in 2 weeks)
    30 days missed    -> ~200 (CRITICAL)
    50 days missed    -> 0 (floor, exam lost)
"""
from collections import defaultdict
from datetime import timedelta
from decimal import Decimal

from django.db import transaction
from django.utils import timezone

MIZAN_ALGORITHM_VERSION = "Mizan_Algorithm_v8.0"
from datetime import date as _mizan_date
MIZAN_RESET_DATE = _mizan_date(2026, 11, 1)  # Day 1 = Nov 1
BASE = 500
SCORE_RANGE = (0, 1000)
WINDOW_DAYS = 120
TOTAL_COURSE_DAYS = 120


def _clamp(v, lo, hi):
    return max(lo, min(hi, v))


def _get_book_count(student):
    """Return the fixed curriculum book count for 9th class.
    
    IMPORTANT: The curriculum has 8 books for 9th class:
    - 7 fixed: Urdu, English, Islamiyat, Mathematics, Chemistry, Physics, Tarjumatul Quran
    - 1 elective: Biology OR Computer Science (student picks ONE, not both)
    
    This function returns 8 for 9th class REGARDLESS of what the SDM table contains,
    because the calendar (curriculum) is the source of truth, not mutable DB rows.
    """
    cls = (student.student_class or '').strip().lower()
    if cls.startswith('9'):
        return 8  # 7 fixed + 1 elective
    
    # For non-9th, use actual DB count
    from exams.models_day_mission import StudentDayMission
    count = StudentDayMission.objects.filter(student=student).values('subject').distinct().count()
    if count == 0:
        from discipline.models import DiaryAssignment
        count = DiaryAssignment.objects.filter(student__linked_code=student.code).values('subject').distinct().count()
    return count if count > 0 else 8


def _earned_trophies(student):
    """Sum of trophy counts from GRADED PHYSICAL PAPER submissions only.

    Uses Sum('count') with count>0 filter to EXCLUDE:
      - RECONCILE:* audit rows (which have count=0)
      - Any future non-paper events with count=0

    Only real Q_COMPLETE events (created by ingest_reports.py from graded
    physical papers) contribute to earned trophies.
    """
    from exams.models_trophy import TrophyEvent
    from django.db.models import Sum
    result = TrophyEvent.objects.filter(
        student=student,
        count__gt=0,
        cancelled_at__isnull=True,
    ).aggregate(total=Sum('count'))
    return result['total'] or 0


def _detailed_question_stats(student):
    """Returns (on_time_count, late_count, missed_count) based on deadline comparison.

    Deadline = end of calendar day N (23:59:59 local).
    Day N calendar date = engine.start_date + (N-1) days.
    """
    from exams.models_day_mission import StudentDayMission
    from exams.models import Submission, AttemptLog, EngineState
    from discipline.models import DiaryAssignment, ClassHomeworkRecord
    from django.utils import timezone
    from datetime import datetime, time as dtime

    engine = EngineState.objects.filter(id=1).first()
    if not engine or not engine.has_started or not engine.start_date:
        return 0, 0, 0
    current_day = engine.get_current_day()

    on_time = 0
    late = 0
    missed = 0

    past_missions = list(StudentDayMission.objects.filter(
        student=student, day_number__lt=current_day
    ).values('day_number', 'question_id'))

    # Prefetch completions for speed
    qids = [m['question_id'] for m in past_missions]
    subs = {}
    for s in Submission.objects.filter(
        exam__student=student, exam__model_question_id__in=qids
    ).order_by('created_at').values('exam__model_question_id', 'created_at'):
        qid = s['exam__model_question_id']
        if qid not in subs:
            subs[qid] = s['created_at']
    atts = {}
    for a in AttemptLog.objects.filter(
        student=student, question_id__in=qids
    ).filter(cancelled_at__isnull=True).order_by('created_at').values('question_id', 'created_at'):
        qid = a['question_id']
        if qid not in atts:
            atts[qid] = a['created_at']

    for m in past_missions:
        deadline_date = engine.start_date + timedelta(days=m['day_number'] - 1)
        try:
            deadline = timezone.make_aware(datetime.combine(deadline_date, dtime(23, 59, 59)))
        except Exception:
            deadline = None

        completed_at = subs.get(m['question_id']) or atts.get(m['question_id'])
        if completed_at is None:
            missed += 1
        elif deadline and completed_at <= deadline:
            on_time += 1
        else:
            late += 1

    # Diary part — completed = on_time, incomplete = missed
    past_diaries = DiaryAssignment.objects.filter(
        student__linked_code=student.code, date__lt=timezone.localdate()
    )
    if past_diaries.exists():
        completed_diaries = set(ClassHomeworkRecord.objects.filter(
            student__linked_code=student.code, star_rating__gt=0
        ).values_list('date', 'subject'))
        for d in past_diaries:
            if (d.date, d.subject) in completed_diaries:
                on_time += 1
            else:
                missed += 1

    return on_time, late, missed



def _health_violation_points(student, window_days=WINDOW_DAYS):
    from exams.models import HealthEvent
    cutoff = timezone.now() - timedelta(days=window_days)
    qs = HealthEvent.objects.filter(student=student, kind="VIOLATION", created_at__gte=cutoff)
    return sum(ev.points for ev in qs)


def _academic_pct(student):
    from exams.models import Exam
    exams = Exam.objects.filter(student=student).exclude(subject__icontains='handwriting').select_related()
    ts = Decimal("0")
    tm = Decimal("0")
    for e in exams:
        sub = e.submissions.order_by("-created_at").first()
        if not sub or sub.ai_score is None or not e.max_marks:
            continue
        ts += sub.ai_score
        tm += e.max_marks
    if tm == 0:
        return None
    return (ts / tm * Decimal("100")).quantize(Decimal("0.01"))


def _presence_pct(student):
    from exams.models import Attendance
    total = Attendance.objects.filter(student=student).count()
    if total == 0:
        return None
    present = Attendance.objects.filter(student=student, present=True).count()
    return (Decimal(present) / Decimal(total) * Decimal("100")).quantize(Decimal("0.01"))


def _ontime_pct(student, days=WINDOW_DAYS):
    from exams.models import StudentTask
    cutoff = timezone.now() - timedelta(days=days)
    qs = StudentTask.objects.filter(student=student, status="DONE", completed_at__gte=cutoff, category="ACADEMIC")
    total = ontime = 0
    for t in qs:
        if not (t.completed_at and t.assigned_at):
            continue
        total += 1
        if (t.completed_at - t.assigned_at) <= timedelta(days=7):
            ontime += 1
    if total == 0:
        return None
    return (Decimal(ontime) / Decimal(total) * Decimal("100")).quantize(Decimal("0.01"))


def _band(score):
    if score < 100:  return "STRUCK_OFF"
    if score < 200:  return "ACTION"
    if score < 300:  return "CRITICAL"
    if score < 400:  return "AT_RISK"
    if score < 500:  return "WATCH"
    if score < 600:  return "NEUTRAL"
    if score < 700:  return "IMPROVING"
    if score < 800:  return "GOOD"
    if score < 900:  return "EXCELLENT"
    return "EXEMPLARY"


def compute(student, window_days=WINDOW_DAYS):
    """Kaifiyat_e_Mizan v8.0 — 9th class only.

    Non-9th students: return current DB score UNCHANGED.
    Non-9th scoring is managed by the point-based ledger
    (discipline/views.py, views_task_hub.py, health.py) — do not touch.
    """
    cls = (student.student_class or '').strip().lower()
    is_9th = cls.startswith('9')

    # ─── 9th CLASS: Mizan Trophy Formula ───
    from exams.models_trophy import TrophyEvent
    from exams.models_day_mission import StudentDayMission
    from exams.models import AttemptLog, EngineState
    from django.db.models import Sum

    pace = student.daily_question_count or 1
    books = _get_book_count(student)
    REFERENCE_PACE = 6
    max_possible = REFERENCE_PACE * books * TOTAL_COURSE_DAYS

    gain_per = 500.0 / max_possible if max_possible else 0.0
    loss_per = 1500.0 / max_possible if max_possible else 0.0

    earned = TrophyEvent.objects.filter(student=student, count__gt=0, cancelled_at__isnull=True).aggregate(total=Sum('count'))['total'] or 0
    gain = earned * gain_per

    missed = 0
    engine = EngineState.objects.filter(id=1).first()
    if engine and engine.has_started:
        current_day = engine.get_current_day()
        reset_day = 1
        try:
            if engine.start_date:
                reset_day = max(1, (MIZAN_RESET_DATE - engine.start_date).days + 1)
        except Exception:
            reset_day = 1
        # INDUSTRY STANDARD: Calendar-based expected workload.
        # Source of truth = curriculum calendar (Nov 1 reset), not mutable DB rows.
        # This is resilient to data loss (SDM deletions, moves, duplicates).
        from django.utils import timezone as _tz
        today = _tz.localdate()
        days_elapsed = max(0, (today - MIZAN_RESET_DATE).days + 1)  # +1 because Nov 1 is Day 1
        books_for_student = _get_book_count(student)
        total_assigned = days_elapsed * pace * books_for_student

        # AUDIT: Compare to actual DB count. If DB < expected, log data-loss alarm.
        db_count = StudentDayMission.objects.filter(student=student).count()
        if db_count < total_assigned * 0.5:
            import logging
            logging.getLogger(__name__).warning(
                'MIZAN_DATA_LOSS student=%s db_sdm=%d expected=%d days_elapsed=%d',
                student.code, db_count, total_assigned, days_elapsed
            )
        
        if not is_9th:
            from discipline.models import DiaryAssignment
            past_diaries = DiaryAssignment.objects.filter(student__linked_code=student.code, date__lt=timezone.localdate())
            for d in past_diaries:
                # If new assignments are set, count them. If not (old data), assume 1 task.
                boxes = sum([d.assigned_handwriting, d.assigned_memorization, d.assigned_understanding, d.assigned_homework, d.assigned_classwork])
                total_assigned += boxes if boxes > 0 else 1
        
        # CONSTITUTIONAL FIX: Missed = Total Assigned - Total Trophies Earned.
        missed = max(0, total_assigned - earned)

    # LOSS = SAME as gain × 3 (explicit)
    # gain per question = gain_per (0.0868)
    # loss per question = gain_per × 3 (0.2604)
    loss = missed * gain_per * 3
    hw_pen = _health_violation_points(student, window_days)

    raw = 500 + gain - loss + hw_pen
    score = int(round(_clamp(raw, *SCORE_RANGE)))

    return {
        "score": score,
        "band": _band(score),
        "earned_trophies": earned,
        "missing_trophies": missed,
        "max_possible": max_possible,
        "gain_per_trophy": round(gain_per, 4),
        "loss_per_trophy": round(loss_per, 4),
        "gain_points": round(gain, 2),
        "loss_points": round(-loss, 2),
        "health_penalties": hw_pen,
        "perfect_days": 0,
        "wrong_questions": 0,
        "absences": 0,
        "lates": 0,
        "completions": earned,
        "penalty_points": round(-loss + hw_pen, 2),
        "credit_points": round(gain, 2),
        "academic_pct": _academic_pct(student),
        "presence_pct": _presence_pct(student),
        "ontime_pct": _ontime_pct(student),
        "window_days": window_days,
        "algorithm_version": MIZAN_ALGORITHM_VERSION,
    }


@transaction.atomic
def recompute(student, write=True):
    """Recompute + persist. Rule 10 (one canonical writer)."""
    from exams.models import HealthScore
    r = compute(student)
    if not write:
        return r
    hs, _ = HealthScore.objects.get_or_create(student=student)
    hs.score = r["score"]
    hs.band = r["band"]
    hs.academic_pct = r["academic_pct"]
    hs.presence_pct = r["presence_pct"]
    hs.ontime_pct = r["ontime_pct"]
    hs.kirdar_delta = int(round(r["gain_points"]))
    hs.penalties = int(round(r["penalty_points"]))
    hs.credit_sum = int(round(r["gain_points"]))
    hs.penalty_sum = int(round(r["penalty_points"]))
    hs.algorithm_version = MIZAN_ALGORITHM_VERSION
    hs.last_recompute_algorithm = MIZAN_ALGORITHM_VERSION
    hs.last_recompute_at = timezone.now()
    hs.save()
    return r
