"""Teacher Operations Center — alert rule engine.

Standards: ITIL 4 Event Management (detect, classify, act);
NIST SP 800-137 (continuous monitoring); Google SRE Ch. 6
(actionable alerts, symptom-based); ISO 9001:2015 9.1.

Six rules. Each returns 0 or more alert dicts:
    {level, code, student, task_id, message_ur, fix_action}

Levels: CRITICAL (immediate action) | WARN (review today) | INFO.
No rule invents facts. Every alert points to a specific row + fix.
"""
from datetime import timedelta
from django.utils import timezone
from exams.models import StudentTask, Student, HealthScore


def _alert(level, code, student, task, message, fix=""):
    return {
        "level": level, "code": code,
        "student_code": student.code if student else "",
        "student_name": student.name if student else "",
        "task_id": task.id if task else None,
        "task_type": task.task_type if task else "",
        "task_ref": task.task_ref if task else "",
        "message_ur": message,
        "fix_action": fix,
    }


def rule_failed_ingest():
    """Any task with ingest_status=FAILED."""
    out = []
    for t in (StudentTask.objects
              .filter(ingest_status="FAILED")
              .select_related("student")[:50]):
        out.append(_alert(
            "CRITICAL", "FAILED_INGEST", t.student, t,
            "%s ka %s task fail hua: %s" % (
                t.student.code, t.task_type,
                (t.ingest_error or "unknown")[:100]),
            "funnel khol kar JSON dobara paste karayein",
        ))
    return out


def rule_mizan_refused():
    """CRITICAL: Mizan REFUSE_WITH_ROUTE tasks wait for teacher decision.

    Mizan sets ingest_status="PENDING" and stores a message beginning
    "Mizan:" in ingest_error when the CS score < 0.50 (ALG-007 §4/§5).
    Without this rule those tasks are silent — the student is stuck,
    the teacher is not notified. This closes DEF-023.
    Standards: ISO 9001:2015 10.2 (corrective action); Google SRE Ch.6
    (actionable alerts); ITIL 4 Event Management; Rule 12 (Mizan gates);
    Rule 23 (single action).
    """
    out = []
    qs = (StudentTask.objects
          .filter(ingest_status="PENDING",
                  ingest_error__startswith="Mizan:")
          .exclude(status="DONE")
          .select_related("student")[:50])
    for t in qs:
        err = (t.ingest_error or "")[:120]
        out.append(_alert(
            "CRITICAL", "MIZAN_REFUSED", t.student, t,
            ("%s ka %s (%s) Mizan ne roka: %s" % (
                t.student.code, t.task_type, t.task_ref, err)),
            ("teacher: accept / edit / reject per ALG-007 s5 "
             "(refuse -> student resubmits correct JSON)"),
        ))
    return out


def rule_repeated_fail(hours=24):
    """Same student, same task type, 2+ failed attempts in window."""
    since = timezone.now() - timedelta(hours=hours)
    out = []
    pairs = {}
    for t in (StudentTask.objects
              .filter(ingest_status="FAILED", last_heartbeat_at__gte=since)
              .select_related("student")):
        k = (t.student_id, t.task_type)
        pairs.setdefault(k, []).append(t)
    for (sid, tt), tasks in pairs.items():
        if len(tasks) >= 2:
            t = tasks[0]
            out.append(_alert(
                "CRITICAL", "REPEATED_FAIL", t.student, t,
                "%s ne %s par %d dafa fail kiya (24 ghante mein)" % (
                    t.student.code, tt, len(tasks)),
                "teacher ke saath baith kar dekhein",
            ))
    return out


def rule_stuck(minutes=45):
    """Task IN_PROGRESS with no heartbeat for > minutes."""
    cutoff = timezone.now() - timedelta(minutes=minutes)
    out = []
    for t in (StudentTask.objects
              .filter(status="IN_PROGRESS",
                      last_heartbeat_at__lt=cutoff)
              .select_related("student")[:50]):
        out.append(_alert(
            "WARN", "STUCK", t.student, t,
            "%s ka %s %d minute se ruka hua hai" % (
                t.student.code, t.task_ref, minutes),
            "student se poochein kahan atka hai",
        ))
    return out


def rule_no_activity():
    """Student has ASSIGNED tasks but no heartbeat today."""
    today = timezone.now().date()
    out = []
    qs = (StudentTask.objects
          .filter(status="ASSIGNED",
                  assigned_at__date=today)
          .select_related("student")
          .order_by("student__code"))
    seen = set()
    for t in qs:
        if t.student_id in seen:
            continue
        seen.add(t.student_id)
        # if this student has any heartbeat today, skip
        if (StudentTask.objects
                .filter(student=t.student, last_heartbeat_at__date=today)
                .exists()):
            continue
        out.append(_alert(
            "WARN", "NO_ACTIVITY", t.student, t,
            "%s ke paas kaam hai magar aaj shuru nahi kiya" % t.student.code,
            "student ko call karein ya task reset karein",
        ))
    return out


def rule_subject_mismatch():
    """KC task assigned to a student not enrolled in that subject."""
    from exams.models import KnowledgeComponent
    out = []
    for t in (StudentTask.objects
              .filter(task_type="KC_MISCONCEPTION", status="ASSIGNED")
              .select_related("student")[:100]):
        kc = KnowledgeComponent.objects.filter(code=t.task_ref).first()
        if not kc:
            continue
        # very conservative check — just log
        out.append(_alert(
            "INFO", "SUBJECT_MISMATCH", t.student, t,
            "%s ko %s KC (%s) mila hai — subject check karein" % (
                t.student.code, t.task_ref, kc.subject),
            "toggle ya assignment adjust karein",
        ))
    return out


def rule_health_drop(drop_threshold=50, hours=24):
    """Health score dropped >= threshold in last N hours."""
    from exams.models import HealthEvent
    from django.db.models import Sum
    since = timezone.now() - timedelta(hours=hours)
    out = []
    for s in Student.objects.filter(is_active=True):
        agg = (HealthEvent.objects
               .filter(student=s, created_at__gte=since)
               .aggregate(total=Sum("points")))
        delta = agg["total"] or 0
        if delta <= -drop_threshold:
            out.append(_alert(
                "WARN", "HEALTH_DROP", s, None,
                "%s ki health %d points giri (24 ghante mein)" % (
                    s.code, delta),
                "teacher health page par jaayein",
            ))
    return out


def all_alerts():
    """Run every rule and return the combined list, sorted by level."""
    alerts = []
    alerts += rule_failed_ingest()
    alerts += rule_mizan_refused()
    alerts += rule_repeated_fail()
    alerts += rule_stuck()
    alerts += rule_no_activity()
    alerts += rule_subject_mismatch()
    alerts += rule_health_drop()
    order = {"CRITICAL": 0, "WARN": 1, "INFO": 2}
    alerts.sort(key=lambda a: (order.get(a["level"], 9),
                               a["student_code"]))
    return alerts
