"""Operations digest — SITREP generator.

Standards: ISO 9001:2015 9.1 (monitoring + analysis);
ITIL 4 Major Incident SITREP pattern; military SITREP convention.
Rule-based, not AI-generated. Every fact cites a row.
"""
from datetime import timedelta, datetime
from zoneinfo import ZoneInfo
from django.utils import timezone
from django.db.models import Count, Q
from exams.models import StudentTask, Student, HealthScore
from exams.alerts import all_alerts


def _count_today(field, value=None):
    today = timezone.now().date()
    qs = StudentTask.objects.filter(assigned_at__date=today)
    if value is None:
        return qs.filter(**{field: True}).count()
    return qs.filter(**{field: value}).count()


def digest_data():
    """Return structured state dict for the ops dashboard."""
    today = timezone.now().date()
    cutoff_15 = timezone.now() - timedelta(minutes=15)

    # LIVE: students with heartbeat in last 15 min
    live = (StudentTask.objects
            .filter(last_heartbeat_at__gte=cutoff_15)
            .select_related("student")
            .order_by("-last_heartbeat_at"))
    live_list = []
    for t in live:
        mins = int((timezone.now() - t.last_heartbeat_at).total_seconds() / 60)
        live_list.append({
            "student_code": t.student.code,
            "student_name": t.student.name,
            "task_type": t.task_type,
            "task_ref": t.task_ref,
            "status": t.status,
            "minutes_ago": mins,
            "task_id": t.id,
        })

    # MATRIX: per-student counts by category
    students = list(Student.objects.filter(is_active=True).order_by("code"))
    matrix = []
    for s in students:
        # Matrix shows all non-skipped work (real current state).
        # Standards: ISO 9001 9.1; Nielsen NN #1 (visibility of truth).
        qs = StudentTask.objects.filter(student=s).exclude(status="SKIPPED")
        acad = qs.filter(category="ACADEMIC")
        mgmt = qs.filter(category="MANAGEMENT")
        matrix.append({
            "student": s,
            "academic_done": acad.filter(status="DONE").count(),
            "academic_total": acad.count(),
            "management_done": mgmt.filter(status="DONE").count(),
            "management_total": mgmt.count(),
            "failed": qs.filter(ingest_status="FAILED").count(),
            "pending": qs.filter(status__in=["ASSIGNED", "IN_PROGRESS"]).count(),
        })

    # counts — today's ACTIVITY (created, completed, or touched today)
    # Standards: ISO 9001:2015 9.1 (measure what matters);
    #   Google SRE Ch. 6 (dashboard reflects truth, not only creation).
    # Robust KPI (Rule 4): completed_at is not reliably set on all DONE
    # rows. Count DONE via any today-touch anchor: heartbeat, step, or
    # completion timestamp. Standards: ISO 9001:2015 9.1 (measure the
    # real thing); Google SRE Ch. 6 (truthful dashboard).
    # Compute Pakistan calendar day boundaries in UTC.
    # WHY: MySQL CONVERT_TZ is unavailable on this shared host; Django's
    # __date lookups rely on it and silently return NULL -> 0 rows.
    # This bypasses CONVERT_TZ entirely.
    # Standards: Google SRE Ch. 6 (truthful dashboard);
    #   ISO 9001:2015 9.1 (measure the real thing); Rule 4 (cite).
    tz_kar = ZoneInfo("Asia/Karachi")
    tz_utc = ZoneInfo("UTC")
    now_kar = timezone.now().astimezone(tz_kar)
    start_kar = datetime(now_kar.year, now_kar.month, now_kar.day, tzinfo=tz_kar)
    end_kar = start_kar + timedelta(days=1)
    start_utc = start_kar.astimezone(tz_utc)
    end_utc = end_kar.astimezone(tz_utc)

    today_anchor = (
        Q(assigned_at__gte=start_utc, assigned_at__lt=end_utc)
        | Q(completed_at__gte=start_utc, completed_at__lt=end_utc)
        | Q(last_heartbeat_at__gte=start_utc, last_heartbeat_at__lt=end_utc)
        | Q(last_step_at__gte=start_utc, last_step_at__lt=end_utc)
    )
    today_touched = StudentTask.objects.filter(today_anchor).exclude(status="SKIPPED")

    # Counts reflect CURRENT state of the today-touched set.
    counts = {
        "total_assigned": today_touched.count(),
        "done": today_touched.filter(status="DONE").count(),
        "in_progress": today_touched.filter(status="IN_PROGRESS").count(),
        "assigned": today_touched.filter(status="ASSIGNED").count(),
        "failed": StudentTask.objects.filter(ingest_status="FAILED").count(),
    }

    alerts = all_alerts()

    return {
        "now": timezone.now(),
        "live_list": live_list,
        "matrix": matrix,
        "counts": counts,
        "alerts": alerts,
        "alert_counts": {
            "CRITICAL": sum(1 for a in alerts if a["level"] == "CRITICAL"),
            "WARN": sum(1 for a in alerts if a["level"] == "WARN"),
            "INFO": sum(1 for a in alerts if a["level"] == "INFO"),
        },
    }


def digest_text():
    """Return the SITREP as plain text — copyable to any AI."""
    d = digest_data()
    lines = []
    lines.append("IDEALOGY SITREP — %s UTC" % d["now"].strftime("%Y-%m-%d %H:%M"))
    lines.append("=" * 60)
    lines.append("")
    lines.append("TODAY'S COUNTS")
    for k, v in d["counts"].items():
        lines.append("  %-18s %d" % (k, v))
    lines.append("")
    lines.append("WORKING NOW (%d students)" % len(d["live_list"]))
    for lv in d["live_list"][:20]:
        lines.append("  %s | %s %s | %s | %d min ago" % (
            lv["student_code"], lv["task_type"], lv["task_ref"],
            lv["status"], lv["minutes_ago"]))
    lines.append("")
    lines.append("ALERTS: %d CRITICAL, %d WARN, %d INFO" % (
        d["alert_counts"]["CRITICAL"],
        d["alert_counts"]["WARN"],
        d["alert_counts"]["INFO"]))
    for a in d["alerts"][:30]:
        lines.append("  [%s] %s: %s" % (a["level"], a["student_code"], a["message_ur"]))
    lines.append("")
    lines.append("TASK: In one paragraph, tell me what to fix first and why.")
    return "\n".join(lines)
