"""PDF report generator - v4.0 (Roman Urdu only, three-section layout)."""
from io import BytesIO
from pathlib import Path

from django.conf import settings
from weasyprint import HTML


CSS = """
@page { size: A4; margin: 1.4cm; }
body { font-family: -apple-system, "Segoe UI", Roboto, sans-serif;
       font-size: 10.5pt; color: #1f2937; line-height: 1.4; }
h1 { font-size: 17pt; margin: 0; color: #1e40af; }
h2 { font-size: 12.5pt; margin: 0.9rem 0 0.4rem; color: #1e40af;
     border-bottom: 1px solid #e5e7eb; padding-bottom: 0.2rem; }
h3 { font-size: 11pt; margin: 0.5rem 0 0.3rem; color: #1e40af; }
.header { border-bottom: 2px solid #1e40af; padding-bottom: 0.4rem;
          margin-bottom: 0.6rem; }
.meta { font-size: 9.5pt; color: #6b7280; margin-top: 0.2rem; }
table { width: 100%; border-collapse: collapse; margin: 0.4rem 0; }
th, td { border: 1px solid #e5e7eb; padding: 0.35rem; text-align: left;
         vertical-align: top; font-size: 9.5pt; }
th { background: #f3f4f6; font-weight: 600; }
.wrong { background: #fef2f2; }
.right { background: #f0fdf4; }
.box { padding: 0.5rem 0.7rem; margin: 0.4rem 0; border-radius: 2px; }
.parent { background: #f0f9ff; border-left: 4px solid #0284c7; }
.parent h2 { border: none; }
.parent ul { margin: 0.3rem 0 0.5rem 1rem; padding: 0; }
.parent li { margin: 0.15rem 0; }
.comment { background: #fef3c7; border-left: 3px solid #d97706; }
.comment b { color: #92400e; }
.model { background: #eef2ff; border-left: 3px solid #4f46e5; }
.story { background: #f0fdf4; border-left: 3px solid #16a34a; }
.task { margin: 0.5rem 0; padding: 0.5rem 0.7rem; background: #f9fafb;
        border-left: 3px solid #1e40af; }
.band-excellent { color: #15803d; font-weight: 700; }
.band-good { color: #65a30d; font-weight: 700; }
.band-fair { color: #d97706; font-weight: 700; }
.band-average { color: #ea580c; font-weight: 700; }
.band-belowaverage, .band-wrong { color: #dc2626; font-weight: 700; }
.q-score { float: right; font-size: 11pt; color: #1e40af; }
"""


def _esc(s):
    if s is None:
        return ""
    text = str(s)
    out = []
    for ch in text:
        out.append(ch if ord(ch) <= 255 else "?")
    text = "".join(out)
    return (text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))


def _band_class(band):
    key = (band or "").replace(" ", "").lower()
    return "band-" + (key or "average")


def _render_parent_summary(summary):
    if not isinstance(summary, dict):
        return ""
    overview = _esc(summary.get("day_overview") or "")
    strengths = summary.get("strengths") or []
    needs = summary.get("needs") or []
    actions = summary.get("actions") or []
    parts = ["<div class=\"box parent\">"]
    parts.append("<h2>Aaj ka din (Walidain ke liye)</h2>")
    if overview:
        parts.append("<p>" + overview + "</p>")
    if strengths:
        parts.append("<b>Acha kaam:</b><ul>")
        for x in strengths:
            parts.append("<li>" + _esc(x) + "</li>")
        parts.append("</ul>")
    if needs:
        parts.append("<b>Sudhaar ki zaroorat:</b><ul>")
        for x in needs:
            parts.append("<li>" + _esc(x) + "</li>")
        parts.append("</ul>")
    if actions:
        parts.append("<b>Aage kya karna hai:</b><ul>")
        for x in actions:
            parts.append("<li>" + _esc(x) + "</li>")
        parts.append("</ul>")
    parts.append("</div>")
    return "".join(parts)


def _render_question_block(idx, exam, sub):
    raw = sub.ai_raw if isinstance(sub.ai_raw, dict) else {}
    band = raw.get("band", "") or ""
    wvc = raw.get("wrong_vs_correct", []) or []
    ec = raw.get("expert_comment", {}) or {}
    mas = raw.get("model_answer_with_story", "") or ""
    score = sub.ai_score if sub.ai_score is not None else "-"
    parts = []
    parts.append("<div class=\"q-block\">")
    parts.append("<h3>Q" + str(idx) + ". " + _esc(exam.subject) +
                 " <span class=\"" + _band_class(band) + "\">" + _esc(band) + "</span>" +
                 "<span class=\"q-score\">" + _esc(score) + " / " + _esc(exam.max_marks) + "</span></h3>")
    if exam.topic:
        parts.append("<div class=\"meta\">Topic: " + _esc(exam.topic) + "</div>")
    if exam.question_text:
        parts.append("<div class=\"meta\"><b>Sawal:</b> " + _esc(exam.question_text) + "</div>")
    if sub.ocr_text:
        parts.append("<div class=\"meta\"><b>Tum ne likha:</b> " + _esc(sub.ocr_text) + "</div>")
    if wvc:
        rows = []
        for w in wvc:
            rows.append("<tr><td class=\"wrong\">" + _esc(w.get("student_wrote")) + "</td>"
                        "<td class=\"right\">" + _esc(w.get("correct_version")) + "</td>"
                        "<td>" + _esc(w.get("error_type")) + "</td></tr>")
        parts.append("<table><thead><tr><th>Ghalat (tum ne likha)</th>"
                     "<th>Sahi (aisa likho)</th><th>Ghalti ki qism</th></tr></thead>"
                     "<tbody>" + "".join(rows) + "</tbody></table>")
    if sub.ai_rationale:
        parts.append("<div class=\"box model\"><b>Tajzia:</b> " + _esc(sub.ai_rationale) + "</div>")
    if mas:
        parts.append("<div class=\"box story\"><b>Model jawab:</b> " + _esc(mas) + "</div>")
    if ec:
        for label, key in (("Acha kiya", "strength"), ("Kaam ki zaroorat", "need"), ("Mashwara", "suggestion")):
            val = ec.get(key)
            if val:
                parts.append("<div class=\"box comment\"><b>" + label + ":</b> " + _esc(val) + "</div>")
    parts.append("</div>")
    return "".join(parts)


def _render_tasks(tasks):
    if not tasks:
        return "<p class=\"meta\">Koi kaam nahi diya gaya.</p>"
    parts = []
    for i, t in enumerate(tasks, 1):
        if isinstance(t, str):
            t = {"title": t}
        title = t.get("title") or ""
        cat = t.get("category") or ""
        ma = t.get("model_answer") or ""
        story = t.get("story_example") or ""
        parts.append("<div class=\"task\">")
        parts.append("<b>Kaam " + str(i) + (" (" + _esc(cat) + ")" if cat else "") + ":</b> " + _esc(title))
        if ma:
            parts.append("<div class=\"box model\"><b>Model jawab:</b> " + _esc(ma) + "</div>")
        if story:
            parts.append("<div class=\"box story\"><b>Kahani se samjho:</b> " + _esc(story) + "</div>")
        parts.append("</div>")
    return "".join(parts)


SOLO_LABELS = {
    0: "Prestructural",
    1: "Unistructural",
    2: "Multistructural",
    3: "Relational",
    4: "Extended abstract",
}


def _render_reflections(student, exam_date):
    """Section 9.8 F: student reflections on stories teaching this exam date.

    Standards: Biggs and Collis (SOLO); Hattie and Timperley (feedback);
    Section 9.7 of the takeover guide.
    """
    from .models import StoryLecture, StoryReflection
    stories = list(StoryLecture.objects.filter(
        source_exam_date=exam_date).order_by("subject", "question_index"))
    if not stories:
        return ""
    reflections = {
        r.story_id: r for r in StoryReflection.objects.filter(
            student=student, story__in=stories).select_related("score")
    }
    parts = ['<h2>Samajhne ka safar (Understanding Path)</h2>']
    for st in stories:
        r = reflections.get(st.id)
        parts.append('<div class="q-block">')
        parts.append('<h3>' + _esc(st.subject) + ' Q' + str(st.question_index)
                     + ' <span class="meta">' + _esc(st.chapter or "") + '</span></h3>')
        parts.append('<div class="meta"><b>Sochne ka sawal:</b> '
                     + _esc(st.comprehension_question) + '</div>')
        if r is None:
            parts.append('<div class="meta">Abhi tak reflection jama nahi ki.</div>')
        else:
            parts.append('<div class="meta"><b>Tum ne likha:</b> '
                         + _esc(r.reflection_text) + '</div>')
            sc = getattr(r, "score", None)
            if sc is not None:
                lbl = SOLO_LABELS.get(sc.solo_level, "")
                parts.append('<div class="box comment"><b>SOLO '
                             + str(sc.solo_level) + ' - ' + _esc(lbl) + '</b></div>')
                if sc.teacher_comment:
                    parts.append('<div class="box model"><b>Teacher ka comment:</b> '
                                 + _esc(sc.teacher_comment) + '</div>')
            else:
                parts.append('<div class="meta">Teacher ne abhi score nahi kiya.</div>')
        parts.append('</div>')
    return "".join(parts)


def build_student_report_html(student, exam_date, items):
    total_score = 0
    total_max = 0
    for e, s in items:
        if s.ai_score is not None:
            total_score = total_score + s.ai_score
        if e.max_marks is not None:
            total_max = total_max + e.max_marks
    mastery = ""
    parent_summary = {}
    tasks = []
    for _e, _s in items:
        _r = _s.ai_raw if isinstance(_s.ai_raw, dict) else {}
        if not mastery and _r.get("mastery_check"):
            mastery = _r.get("mastery_check")
        if not parent_summary and _r.get("parent_summary"):
            parent_summary = _r.get("parent_summary")
        if not tasks and _r.get("next_day_tasks"):
            tasks = _r.get("next_day_tasks")
        if mastery and parent_summary and tasks:
            break
    q_blocks = "".join(_render_question_block(i, e, s) for i, (e, s) in enumerate(items, 1))
    body = []
    body.append("<!doctype html><html><head><meta charset=\"utf-8\">")
    body.append("<style>" + CSS + "</style></head><body>")
    body.append("<div class=\"header\">")
    body.append("<h1>Idealogy Academy - Rozana Report</h1>")
    body.append("<div class=\"meta\">")
    body.append("Student: <strong>" + _esc(student.name) + "</strong> (" + _esc(student.code) + ") - ")
    body.append("Tier " + str(student.tier) + " - " + _esc(student.get_student_class_display()))
    body.append("<br>Date: " + _esc(exam_date) + " - Total: <b>" + _esc(total_score) + " / " + _esc(total_max) + "</b>")
    body.append("</div></div>")
    body.append(_render_parent_summary(parent_summary))
    body.append("<h2>Sawal aur Jawab</h2>")
    body.append(q_blocks)
    body.append("<h2>Aaj ke Kaam</h2>")
    body.append(_render_tasks(tasks))
    body.append(_render_reflections(student, exam_date))
    body.append("<h2>Kal ka Test</h2>")
    body.append("<div class=\"box model\">" + (_esc(mastery) or "Kal wohi sawal dobara karein.") + "</div>")
    body.append("</body></html>")
    return "".join(body)


def save_student_report_pdf(student, exam_date, items, out_dir=None):
    if out_dir is None:
        out_dir = Path(settings.BASE_DIR).parent / "output" / "daily_reports"
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    fname = student.code + "_" + student.name.replace(" ", "_") + "_" + str(exam_date) + ".pdf"
    path = out_dir / fname
    html = build_student_report_html(student, exam_date, items)
    path.write_bytes(HTML(string=html).write_pdf())
    return path


# --- Backward compat: single-question API (may be referenced by older code) ---


def build_report_html(exam, submission):
    return build_student_report_html(exam.student, exam.exam_date, [(exam, submission)])


def render_report_pdf(exam, submission) -> bytes:
    html = build_report_html(exam, submission)
    return HTML(string=html).write_pdf()


def save_report_pdf(exam, submission, out_dir=None) -> Path:
    if out_dir is None:
        out_dir = Path(settings.BASE_DIR).parent / "output" / "daily_reports"
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    fname = exam.student.code + "_" + exam.student.name.replace(" ", "_") + "_" + str(exam.exam_date) + ".pdf"
    path = out_dir / fname
    path.write_bytes(render_report_pdf(exam, submission))
    return path


# =====================================================================
# Monthly Report Card (Task 5.5) - measured-data only
#
# Standards: AERA/APA/NCME 2014 Std 13.7 (each reported value names
# its construct); Guskey, On Your Mark 3rd ed. 2020 (communication
# device); Wiggins & McTighe 2005; Hattie & Timperley 2007 (where am
# I going / how am I going / where to next); ESSA Report Card Design;
# NSW DoE plain-language 2025; DBI/MTSS progress monitoring (slope
# within period); BISE Gujranwala 9th class 550 marks, 33% pass
# (Section 15.1 SC3); Biggs & Collis SOLO; ISO 9001:2015 7.5.3;
# ISO 9241-210; Rule 8 (Roman Urdu, no YouTube URLs in Latin-1 PDF);
# Rule 10 (single canonical writer - this module).
#
# ONLY values traceable to a stored model.field appear on the card.
# The external reference (~/idealogy/design/REPORT_CARD_REFERENCE.md)
# is inspiration; the field list is fixed in
# ~/idealogy/design/REPORT_CARD_DESIGN_v2.md.
# =====================================================================

REPORT_CARD_CSS = """
@page { size: A4; margin: 1.2cm; }
body { font-family: -apple-system, "Segoe UI", Roboto, sans-serif;
       font-size: 10pt; color: #1f2937; line-height: 1.4; }
h1 { font-size: 16pt; margin: 0; color: #1e40af; }
h2 { font-size: 11.5pt; margin: 0.9rem 0 0.4rem; color: #1e40af;
     border-bottom: 1px solid #e5e7eb; padding-bottom: 0.2rem; }
h3 { font-size: 10pt; margin: 0.5rem 0 0.3rem; color: #1e40af; }
.header { border-bottom: 2px solid #1e40af; padding-bottom: 0.4rem;
          margin-bottom: 0.6rem; }
.meta { font-size: 9pt; color: #4b5563; margin-top: 0.15rem; }
table { width: 100%; border-collapse: collapse; margin: 0.3rem 0; }
th, td { border: 1px solid #e5e7eb; padding: 0.3rem 0.4rem;
         text-align: left; vertical-align: top; font-size: 9pt; }
th { background: #f3f4f6; font-weight: 600; }
.kpis { display: grid; grid-template-columns: repeat(4, 1fr);
        gap: 0.4rem; margin: 0.5rem 0; }
.kpi { background: #f9fafb; border-left: 3px solid #1e40af;
       padding: 0.4rem 0.6rem; }
.kpi b { display: block; font-size: 13pt; color: #1e40af; }
.kpi span { font-size: 8.5pt; color: #6b7280; }
.kpi.good b { color: #15803d; }
.kpi.warn b { color: #b45309; }
.kpi.low b { color: #b91c1c; }
.box { padding: 0.4rem 0.6rem; margin: 0.3rem 0; border-radius: 2px; }
.strengths { background: #f0fdf4; border-left: 3px solid #15803d; }
.needs { background: #fef2f2; border-left: 3px solid #b91c1c; }
.actions { background: #eff6ff; border-left: 3px solid #1e40af; }
.observation { background: #fffbeb; border-left: 3px solid #b45309;
               margin: 0.25rem 0; padding: 0.35rem 0.6rem; }
.observation .dom { font-weight: 700; font-size: 8.5pt;
                    text-transform: uppercase; color: #92400e; }
.trend-up { color: #15803d; font-weight: 700; }
.trend-down { color: #b91c1c; font-weight: 700; }
.trend-flat { color: #6b7280; }
.signature { margin-top: 1.2rem; padding-top: 0.6rem;
             border-top: 1px solid #e5e7eb; font-size: 9pt; }
.signature .line { margin-top: 1.2rem; border-bottom: 1px solid #9ca3af;
                   width: 60%; }
.teacher-only { background: #f3f4f6; border-left: 3px solid #6b7280;
                padding: 0.3rem 0.6rem; font-size: 8.5pt;
                color: #4b5563; margin: 0.3rem 0; }
"""


def _band_from_pct(pct):
    """Three-band classification consistent with portal_dashboard._band().

    Reused (not forked) so the report card and the portal agree
    (Rule 10). The values mirror exams.views._band via delegation if
    available, otherwise recomputed here with the same thresholds.
    """
    try:
        from .views import _band
        return _band(pct)
    except Exception:
        if pct >= 70:
            return {"key": "good", "label": "Acha", "icon": ""}
        if pct >= 50:
            return {"key": "average", "label": "Darmiyana", "icon": ""}
        return {"key": "low", "label": "Kaam baqi", "icon": ""}


def _month_subject_rows(student, date_from, date_to):
    """Aggregate Exam + latest Submission per subject in the period."""
    from .models import Exam
    exams = (
        Exam.objects.filter(student=student,
                            exam_date__gte=date_from,
                            exam_date__lte=date_to)
        .select_related("student")
        .order_by("subject", "exam_date", "question_index")
    )
    by_subj = {}
    for e in exams:
        sub = e.submissions.order_by("-created_at").first()
        if sub is None or sub.ai_score is None:
            continue
        slot = by_subj.setdefault(e.subject, {"scores": [], "maxes": [], "items": 0})
        slot["scores"].append(float(sub.ai_score))
        slot["maxes"].append(float(e.max_marks or 0))
        slot["items"] += 1
    rows = []
    for subj, d in by_subj.items():
        total_max = sum(d["maxes"]) or 0
        total_score = sum(d["scores"])
        pct = round(total_score / total_max * 100, 1) if total_max else 0
        band = _band_from_pct(pct)
        # Within-period trend: last 3 vs first 3 by score fraction
        fracs = [s / m for s, m in zip(d["scores"], d["maxes"]) if m]
        trend = "flat"
        if len(fracs) >= 4:
            first3 = sum(fracs[:3]) / 3
            last3 = sum(fracs[-3:]) / 3
            if last3 - first3 > 0.05:
                trend = "up"
            elif first3 - last3 > 0.05:
                trend = "down"
        rows.append({
            "subject": subj,
            "items": d["items"],
            "total_score": round(total_score, 2),
            "total_max": round(total_max, 2),
            "pct": pct,
            "band": band,
            "trend": trend,
        })
    rows.sort(key=lambda r: r["subject"])
    return rows


def _period_kpis(student, date_from, date_to):
    from .models import Attendance, DailyTask, Exam, StoryReflection, ReflectionScore
    att_total = Attendance.objects.filter(
        student=student, date__gte=date_from, date__lte=date_to).count()
    att_present = Attendance.objects.filter(
        student=student, date__gte=date_from, date__lte=date_to,
        present=True).count()
    att_pct = round(att_present / att_total * 100, 1) if att_total else 0

    tk_total = DailyTask.objects.filter(
        student=student, date_due__gte=date_from, date_due__lte=date_to).count()
    tk_done = DailyTask.objects.filter(
        student=student, date_due__gte=date_from, date_due__lte=date_to,
        completed=True).count()
    tk_pct = round(tk_done / tk_total * 100, 1) if tk_total else 0

    exam_items = 0
    total_score = 0.0
    total_max = 0.0
    for e in Exam.objects.filter(student=student,
                                 exam_date__gte=date_from,
                                 exam_date__lte=date_to):
        sub = e.submissions.order_by("-created_at").first()
        if sub is None or sub.ai_score is None:
            continue
        exam_items += 1
        total_score += float(sub.ai_score)
        total_max += float(e.max_marks or 0)
    overall_pct = round(total_score / total_max * 100, 1) if total_max else 0

    reflections = StoryReflection.objects.filter(
        student=student, submitted_at__date__gte=date_from,
        submitted_at__date__lte=date_to).count()
    solo_scores = list(ReflectionScore.objects.filter(
        reflection__student=student,
        reflection__submitted_at__date__gte=date_from,
        reflection__submitted_at__date__lte=date_to,
    ).values_list("solo_level", flat=True))
    solo_avg = round(sum(solo_scores) / len(solo_scores), 2) if solo_scores else None

    # BISE Gujranwala 9th class: 33% pass, safe at 40% (Section 15.1 SC3)
    if overall_pct >= 40:
        proj = "Board projection: SAFE (40% se upar)"
    elif overall_pct >= 33:
        proj = "Board projection: PASS margin (33-40%)"
    else:
        proj = "Board projection: RISK (33% se kam)"

    return {
        "att_pct": att_pct, "att_present": att_present, "att_total": att_total,
        "tk_pct": tk_pct, "tk_done": tk_done, "tk_total": tk_total,
        "exam_items": exam_items,
        "overall_pct": overall_pct,
        "total_score": round(total_score, 2),
        "total_max": round(total_max, 2),
        "reflections": reflections,
        "solo_avg": solo_avg,
        "solo_n": len(solo_scores),
        "board_projection": proj,
    }


def _period_observations(student, date_from, date_to, include_parent_only):
    from .models import StudentProfile, ProfileEntry
    try:
        prof = StudentProfile.objects.get(student=student)
    except StudentProfile.DoesNotExist:
        return []
    qs = ProfileEntry.objects.filter(
        profile=prof, entry_date__gte=date_from, entry_date__lte=date_to,
    ).order_by("entry_date")
    if include_parent_only:
        qs = qs.filter(parent_visible=True)
    return list(qs)


def _render_hw_rd_block(report):
    """Likhai aur Padhai block for the monthly card.

    Standards: DASH-2 (handwriting); Hasbrouck-Tindal 2017 (ORF);
    AERA/APA/NCME 2014 Std 1.0 (each value names its construct);
    Rule G (Roman Urdu labels).
    """
    s = getattr(report, "hw_rd_summary", None) or {}
    if not s.get("by_skill"):
        return ""
    rows = []
    for label, d in s["by_skill"].items():
        rows.append(
            "<tr><td>" + _esc(label) + "</td>"
            "<td style='text-align:right'>" + str(d.get("done", 0)) + "</td>"
            "<td style='text-align:right'>" + str(d.get("open", 0)) + "</td>"
            "<td style='text-align:right'>" + str(d.get("assessed", 0)) + "</td></tr>"
        )
    return (
        "<h2>Likhai aur Padhai</h2>"
        "<table style='width:100%;border-collapse:collapse;font-size:.9rem'>"
        "<thead><tr style='border-bottom:1px solid #e5e7eb'>"
        "<th style='text-align:left'>Qism</th>"
        "<th style='text-align:right'>Mukammal</th>"
        "<th style='text-align:right'>Baqi</th>"
        "<th style='text-align:right'>Jaanch</th>"
        "</tr></thead><tbody>" + "".join(rows) + "</tbody></table>"
    )


def _render_kzm_block(report):
    """Kaifiyat_e_Mizan snapshot block for the monthly card.

    Reads report.kzm_score and report.kzm_band — the values computed at
    report-build time (AERA Std 1.0; a value names its construct; the PDF
    always shows the value that was current when the report was built,
    not a value recomputed on view). Rule I (Kaifiyat_e_Mizan spelling).
    Rule G (Roman Urdu band label).
    """
    score = getattr(report, "kzm_score", None)
    band = getattr(report, "kzm_band", "") or ""
    if score is None:
        return ""
    labels = {
        "STRUCK_OFF": "Academy se nikal diya gaya",
        "ACTION": "Waza'ati karwai",
        "CRITICAL": "Bohat kharab",
        "AT_RISK": "Khatre mein",
        "WATCH": "Nazar rakhein",
        "NEUTRAL": "Naya safar",
        "IMPROVING": "Behtar hota hua",
        "GOOD": "Achi halat",
        "EXCELLENT": "Behtareen",
        "EXEMPLARY": "Misali",
    }
    tones = {
        "STRUCK_OFF": ("#f4e3db", "#6f3331", "#b50909"),
        "ACTION":     ("#faeaea", "#7f1d1d", "#dc2626"),
        "CRITICAL":   ("#fef2f2", "#991b1b", "#ef4444"),
        "AT_RISK":    ("#fff7ed", "#7c2d12", "#ea580c"),
        "WATCH":      ("#fffbeb", "#92400e", "#d97706"),
        "NEUTRAL":    ("#f9fafb", "#374151", "#6b7280"),
        "IMPROVING":  ("#ecfdf5", "#166534", "#22c55e"),
        "GOOD":       ("#f0fdf4", "#166534", "#15803d"),
        "EXCELLENT":  ("#ecf3ec", "#14532d", "#16a34a"),
        "EXEMPLARY":  ("#dcfce7", "#052e16", "#15803d"),
    }
    tint, text, border = tones.get(band, ("#f9fafb", "#374151", "#6b7280"))
    label = labels.get(band, band or "-")
    return (
        "<h2>Kaifiyat_e_Mizan</h2>"
        "<div style='border-left:8px solid " + border + ";background:" + tint +
        ";padding:.9rem 1rem;border-radius:8px;margin:.3rem 0 1rem'>"
        "<div style='font-size:1.6rem;font-weight:800;color:" + text +
        ";font-variant-numeric:tabular-nums'>" + _esc(str(score)) + " / 1000</div>"
        "<div style='font-weight:700;color:" + text + ";margin-top:.15rem'>" +
        _esc(label) + "</div>"
        "</div>"
    )


def build_result_card_html(report):
    """Render a monthly ParentReport row as a printable report card.

    Only values traceable to stored model fields appear. Constructs not
    measured by Idealogy are omitted (teacher directive 2026-10-05;
    AERA/APA/NCME 2014 Std 13.7).
    """
    student = report.student
    date_from = report.date_from
    date_to = report.date_to
    kpis = _period_kpis(student, date_from, date_to)
    rows = _month_subject_rows(student, date_from, date_to)
    teacher_obs = _period_observations(student, date_from, date_to,
                                       include_parent_only=False)
    parent_obs = [o for o in teacher_obs if o.parent_visible]
    has_parent_obs = len(parent_obs) > 0
    # Phase 5: measured red flags + passing chance
    from exams.red_flags import compute_red_flags, passing_chance
    _rfs = compute_red_flags(student)
    _pc = passing_chance(student)

    def kpi(pct, good_thresh, warn_thresh):
        if pct >= good_thresh:
            return "good"
        if pct >= warn_thresh:
            return "warn"
        return "low"

    b = []
    b.append("<!doctype html><html><head><meta charset=\"utf-8\">")
    b.append("<style>" + REPORT_CARD_CSS + "</style></head><body>")
    b.append("<div class=\"header\">")
    b.append("<h1>Idealogy Academy - Mahana Report Card</h1>")
    b.append("<div class=\"meta\">")
    b.append("<strong>" + _esc(student.name) + "</strong> (" + _esc(student.code) + ")")
    if student.father_name:
        b.append(" - Walid: " + _esc(student.father_name))
    b.append("<br>Class: " + _esc(student.get_student_class_display())
             + " - Tier " + str(student.tier))
    if student.shift:
        b.append(" - Shift: " + _esc(student.get_shift_display() if hasattr(student, 'get_shift_display') else student.shift))
    b.append("<br>Period: " + _esc(str(date_from)) + " to " + _esc(str(date_to)))
    b.append("</div></div>")

    if _rfs:
        b.append("<div class=\"box needs\">")
        b.append("<strong>DEKHEIN, YEH RED FLAGS HAIN</strong>")
        b.append("<p>Aap ke account par abhi " + str(len(_rfs))
                 + " red flag(s) hain:</p><ul>")
        for _rf in _rfs:
            b.append("<li>" + _esc(_rf["label_ur"]) + " &mdash; "
                     + _esc(_rf["value"]) + " (threshold "
                     + _esc(_rf["threshold"]) + "; standard: "
                     + _esc(_rf["standard"]) + ") &mdash; "
                     + _esc(_rf["action_ur"]) + "</li>")
        b.append("</ul>")
        if _pc["ready"]:
            b.append("<p>Passing chance: " + str(_pc.get("pct"))
                     + "% (CI " + str(_pc.get("ci")) + ") model="
                     + _esc(_pc.get("model", "v1")) + "</p>")
        else:
            b.append("<p>Passing chance: INSUFFICIENT DATA - "
                     + _esc(", ".join(_pc["missing"])) + "</p>")
        b.append("<p>[ Sudharne ka plan dekhein ]   [ Madad chahiye ]</p>")
        b.append("</div>")
    elif not _pc["ready"]:
        b.append("<div class=\"box\">Passing chance: INSUFFICIENT DATA - "
                 + _esc(", ".join(_pc["missing"])) + "</div>")

    b.append("<h2>Ek nazar mein</h2>")
    b.append("<div class=\"kpis\">")
    b.append("<div class=\"kpi " + kpi(kpis['overall_pct'], 70, 50) + "\">"
             "<b>" + _esc(str(kpis['overall_pct'])) + "%</b>"
             "<span>Academic (" + _esc(str(kpis['total_score'])) + "/"
             + _esc(str(kpis['total_max'])) + ")</span></div>")
    b.append("<div class=\"kpi " + kpi(kpis['att_pct'], 90, 75) + "\">"
             "<b>" + _esc(str(kpis['att_pct'])) + "%</b>"
             "<span>Attendance (" + str(kpis['att_present']) + "/"
             + str(kpis['att_total']) + ")</span></div>")
    b.append("<div class=\"kpi " + kpi(kpis['tk_pct'], 80, 50) + "\">"
             "<b>" + _esc(str(kpis['tk_pct'])) + "%</b>"
             "<span>Homework (" + str(kpis['tk_done']) + "/"
             + str(kpis['tk_total']) + ")</span></div>")
    solo_txt = (str(kpis['solo_avg']) + " / 4") if kpis['solo_avg'] is not None else "no data"
    b.append("<div class=\"kpi\"><b>" + _esc(solo_txt) + "</b>"
             "<span>SOLO average (" + str(kpis['solo_n']) + " scored)</span></div>")
    b.append("</div>")

    b.append("<h2>Subject-wise (measured in this period)</h2>")
    if rows:
        b.append("<table><thead><tr>"
                 "<th>Subject</th><th>Tests</th><th>Score</th>"
                 "<th>Percent</th><th>Band</th><th>Trend</th></tr></thead><tbody>")
        for r in rows:
            if r["trend"] == "up":
                t = "<span class=\"trend-up\">up</span>"
            elif r["trend"] == "down":
                t = "<span class=\"trend-down\">down</span>"
            else:
                t = "<span class=\"trend-flat\">flat</span>"
            b.append("<tr><td>" + _esc(r["subject"]) + "</td>"
                     "<td>" + str(r["items"]) + "</td>"
                     "<td>" + _esc(str(r["total_score"])) + " / " + _esc(str(r["total_max"])) + "</td>"
                     "<td>" + _esc(str(r["pct"])) + "%</td>"
                     "<td>" + _esc(r["band"]["label"]) + "</td>"
                     "<td>" + t + "</td></tr>")
        b.append("</tbody></table>")
    else:
        b.append("<p class=\"meta\">Is period mein koi graded test nahi hua.</p>")

    if report.strengths:
        b.append("<h2>Achi baatein</h2>")
        b.append("<div class=\"box strengths\">" + _esc(report.strengths) + "</div>")
    if report.weaknesses:
        b.append("<h2>Sudhaar ki gunjaish</h2>")
        b.append("<div class=\"box needs\">" + _esc(report.weaknesses) + "</div>")
    if report.action_items:
        b.append("<h2>Aage kya karna hai</h2>")
        b.append("<div class=\"box actions\">" + _esc(report.action_items) + "</div>")

    if kpis["reflections"]:
        b.append("<h2>Samajhne ka safar</h2>")
        b.append("<p class=\"meta\">Reflections jama: " + str(kpis["reflections"]))
        if kpis["solo_avg"] is not None:
            b.append(" - SOLO average: " + _esc(str(kpis["solo_avg"])) + " / 4")
        b.append("</p>")

    _hwrd_html = _render_hw_rd_block(report)
    if _hwrd_html:
        b.append(_hwrd_html)

    b.append("<h2>Board projection (BISE Gujranwala - teacher reference)</h2>")
    b.append("<div class=\"teacher-only\">" + _esc(kpis["board_projection"]) + "</div>")

    if has_parent_obs:
        b.append("<h2>Teacher ke mushahiday</h2>")
        for o in parent_obs:
            b.append("<div class=\"observation\">"
                     "<span class=\"dom\">" + _esc(o.domain) + " - "
                     + _esc(str(o.entry_date)) + "</span><br>"
                     + _esc(o.observed) + "</div>")

    _kzm_html = _render_kzm_block(report)
    if _kzm_html:
        b.append(_kzm_html)

    b.append("</body></html>")
    return "".join(b)


def save_result_card_pdf(report, out_dir=None):
    """Write the monthly report card PDF for one ParentReport row."""
    if out_dir is None:
        out_dir = Path(settings.BASE_DIR).parent / "output" / "result_cards"
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    fname = (report.student.code + "_" + report.student.name.replace(" ", "_")
             + "_" + str(report.date_from) + "_to_" + str(report.date_to) + ".pdf")
    path = out_dir / fname
    html = build_result_card_html(report)
    path.write_bytes(HTML(string=html).write_pdf())
    return path
