"""Shared view helpers for exams app.

Extracted from views.py 2026-11-09 (Handover V2 Phase 2, helper surgery).

Rationale:
    _is_teacher is a 2-line pure predicate used by 41 decorator sites in
    views.py and by 5+ external modules (discipline, integrity, story_review,
    question_errors, content_gaps). Extracting view clusters that ALSO use
    _is_teacher (e.g., views_health.py) requires this helper to live in a
    neutral module — otherwise views.py importing views_health.py (facade)
    plus views_health.py importing views.py (_is_teacher) creates a cycle.

Design rules for this module:
    - Pure functions only. No Django model imports, no DB access.
    - No imports from `.views`, `.views_*`, or `.models` — this guarantees
      the module can never participate in an import cycle.
    - Add a helper only when at least TWO sibling modules need it.
      Single-consumer helpers stay local to their module.
"""

from django.shortcuts import redirect
from django.http import Http404


def _is_teacher(user):
    return user.is_authenticated and user.is_active and user.is_staff


def _paper_from_book(book_code):
    """MT-9-BOOK -> MT-9 ; CH-9-P05 -> CH-9 (subject bank code)."""
    if not book_code:
        return ""
    if book_code.endswith("-BOOK"):
        return book_code[:-5]
    parts = book_code.split("-")
    if len(parts) >= 2:
        return parts[0] + "-" + parts[1]
    return book_code


def _compute_pipeline_status(pipe):
    """Canonical status for a pipeline. ONE writer (Rule 10).

    Turn 4 (2026-10-11). Teacher stages (2, 4, 8, 9) -> BLOCKED_ON_TEACHER.
    All 11 stages done -> DONE. Otherwise -> ACTIVE.

    Standards: Cooper Stage-Gate; PIPELINE_STAGES defines 11 stages;
    Rule 10 (one canonical writer); AERA 2014 Std 1.0 (status names
    its construct); Nielsen NN #1 (teacher sees gate button).
    """
    done = set(pipe.stages_completed or [])
    if len(done) >= 11:
        return "DONE"
    nxt = next((s for s in range(1, 12) if s not in done), None)
    if nxt is None:
        return "DONE"
    if nxt in (2, 4, 8, 9):
        return "BLOCKED_ON_TEACHER"
    return "ACTIVE"

# Pipeline stage → task type mapping. Used by _create_pipeline_task_for_stage
# in view_db_helpers.py and by _advance_pipeline / _advance_pipeline_legacy
# in views.py. Moved here 2026-11-09 to break the views ↔ view_db_helpers
# import cycle that would result from defining it in views.py.
STAGE_TO_TASK_TYPE = {
    3: "KC_DISCOVERY",
    5: "KC_TAG",
    6: "KC_MISCONCEPTION",
    7: "KC_SOCRATIC_LADDER",
    10: "GLOSSARY",
    11: "STORY",
}


# Constants used by extracted teacher view functions (2026-11-09).
# Moved from views.py alongside Wave 3 extraction to break the
# views.py ↔ views_teacher.py import cycle.

SAFEGUARD_FEATURES = [
    ("feature.task_portal",    "Task portal (Mere Kaam)",        "student,parent"),
    ("feature.support_ticket", "Support tickets",                 "student,parent"),
    ("feature.parent_message", "Teacher-parent messages",         "parent"),
    ("feature.kc_discovery",   "KC discovery tasks",              "student"),
    ("feature.kc_tag",         "KC tag tasks",                    "student"),
    ("feature.glossary",       "Glossary tasks",                  "student"),
    ("feature.story",          "Story lecture tasks",             "student"),
]

PIPELINE_STAGES = [
    (1,  "Photo + prompt -> Gemini", "student", True),
    (2,  "Ingest bank mein",         "system",  False),
    (3,  "KC discovery",             "student", True),
    (4,  "KC discovery review",      "teacher", False),
    (5,  "KC tag",                   "student", True),
    (6,  "KC misconception",         "student", True),
    (7,  "KC socratic ladder",       "student", True),
    (8,  "Quality gate",             "teacher", False),
    (9,  "Prompt freeze",            "teacher", False),
    (10, "Glossary",                 "student", True),
    (11, "Story lecture",            "student", True),
]


# Teacher subject constants (moved from views.py 2026-11-09)
_SUBJECT_CHOICES = [
    ("",               "(koi nahi)"),
    ("Chemistry",      "Chemistry"),
    ("Biology",        "Biology"),
    ("Physics",        "Physics"),
    ("Mathematics",    "Mathematics"),
    ("English",        "English"),
    ("Islamiat",       "Islamiat"),
    ("Urdu",           "Urdu"),
    ("ComputerScience","Computer Science"),
    ("Tajweed",        "Tajweed"),
    ("TarjumatulQuran","Tarjumatul Quran"),
]

_SUBJECT_DEFAULT_BOOK = {
    "Chemistry":       "CH-9-BOOK",
    "Biology":         "BI-9-BOOK",
    "Physics":         "PH-9-BOOK",
    "Mathematics":     "MT-9-BOOK",
    "English":         "EN-9-BOOK",
    "Islamiat":        "IS-9-BOOK",
    "Pak Study":       "PS-10-BOOK",
    "Urdu":            "UR-9-BOOK",
    "ComputerScience": "CS-9-BOOK",
    "Tajweed":         "TJ-9-BOOK",
    "TarjumatulQuran": "TQ-9-BOOK",
}




def _student_enrolled_subjects(student):
    """Thin shim - delegates to the canonical reader (Rule 10).
    Reads Student.enrolled_subjects only. No derivation. No fallback.
    Empty list means not yet declared; caller MUST deny (fail-safe).
    """
    from exams.enrollment import enrolled_prefixes
    return enrolled_prefixes(student)


_SUBJECT_TO_PREFIX = {
    "Mathematics": "MT", "Physics": "PH", "Chemistry": "CH",
    "Biology": "BI", "English": "EN", "Urdu": "UR",
    "Islamiyat": "IS", "Computer Science": "CS", "Tarjumatul Quran": "TQ",
    'Civics': 'CV',
    'Economic': 'EC',
    'Islamiyat Optional': 'IO',
}


def _no_student_redirect(request):
    """Logged-in user has no student record. Staff -> teacher hub. Other -> 404."""
    if request.user.is_superuser or request.user.is_staff:
        return redirect('/api/portal/teacher/hub/')
    raise Http404("Student link not found.")


def _board_prediction(student, total_trophies, current_day):
    """Board exam prediction based on current pace.

    Each tier produces a grammatically correct sentence.
    Positive tiers (>=16/day): "you will get X"
    At-risk tiers (<16/day): warning message, NOT a false promise
    """
    if current_day < 1:
        return {
            'pace': 0,
            'pace_display': 0,
            'outcome': 'engine not started',
            'message': "Abhi engine shuru nahi hua.",
            'color': '#6b7280',
            'current_tier': 0,
            'show': False,
        }

    pace = round(total_trophies / current_day, 1)
    pace_display = int(round(pace))  # clean integer for display

    if total_trophies < 1:
        return {
            'pace': pace,
            'pace_display': pace_display,
            'outcome': 'shuru nahi kiya',
            'message': (
                "Aap ne abhi tak koi trophy nahi kamayi. "
                "Board exam mein achay marks ke liye rozana 24+ trophies zaroori hain — "
                "aaj se shuru karein."
            ),
            'color': '#f59e0b',
            'current_tier': 0,
            'show': True,
        }

    if pace >= 40:
        outcome = "maximum marks"
        color = "#10b981"
        current_tier = 1
        message = (
            f"Agar aap isi raftaar (rozana {pace_display} trophies) se chaltay rahein, "
            f"to board exam mein aap ko maximum marks milne ki umeed hai."
        )
    elif pace >= 32:
        outcome = "800+ marks"
        color = "#3b82f6"
        current_tier = 2
        message = (
            f"Agar aap isi raftaar (rozana {pace_display} trophies) se chaltay rahein, "
            f"to board exam mein aap ko 800+ marks milne ki umeed hai."
        )
    elif pace >= 24:
        outcome = "passing marks"
        color = "#f59e0b"
        current_tier = 3
        message = (
            f"Agar aap isi raftaar (rozana {pace_display} trophies) se chaltay rahein, "
            f"to board exam mein aap ko passing marks milne ki umeed hai."
        )
    elif pace >= 16:
        outcome = "6 mein se 8 books pass"
        color = "#f97316"
        current_tier = 4
        message = (
            f"Agar aap isi raftaar (rozana {pace_display} trophies) se chaltay rahein, "
            f"to aap 8 mein se 6 books pass kar lenge. "
            f"Board exam pass karne ke liye rozana 24+ trophies zaroori hain."
        )
    elif pace >= 8:
        outcome = "4 mein se 8 books pass"
        color = "#ef4444"
        current_tier = 5
        message = (
            f"Aap ki maujooda raftaar (rozana {pace_display} trophies) sirf 4 books "
            f"pass karne ke liye kaafi hai. Board exam pass karne ke liye rozana "
            f"24+ trophies zaroori hain — foran mehnat shuru karein."
        )
    else:
        outcome = "board exam at risk"
        color = "#dc2626"
        current_tier = 0
        message = (
            f"Aap ki maujooda raftaar (rozana {pace_display} trophies) board exam "
            f"ke liye khatarnaak hai. Pass hone ke liye rozana 24+ trophies zaroori "
            f"hain — aaj se mehnat shuru karein."
        )

    return {
        'pace': pace,
        'pace_display': pace_display,
        'outcome': outcome,
        'message': message,
        'color': color,
        'current_tier': current_tier,
        'show': True,
    }


def _band(pct):
    if pct >= 70:
        return {"key": "good", "label": "Acha", "icon": "✓"}
    if pct >= 50:
        return {"key": "warn", "label": "Theek", "icon": "!"}
    return {"key": "low", "label": "Kaam zaroori", "icon": "x"}


_SUBJECT_FOLDERS = {
    "CH": "Chemistry", "BI": "Biology", "PH": "Physics",
    "MT": "Mathematics", "EN": "English", "IS": "Islamiat",
    "UR": "Urdu", "CS": "ComputerScience", "TJ": "Tajweed",
    "TQ": "TarjumatulQuran", "PS": "PakStudy",
}


GEM_STAGES = {
    1: ("GEM-KC-DISCOVERY",     "KC Discovery",         "kcs",        "Discovery"),
    2: ("GEM-KC-TAG",           "KC Tag",               "tags",       "Tag"),
    3: ("GEM-KC-MISCONCEPTION", "KC Misconception",     "candidates", "Misconception"),
    4: ("GEM-KC-LADDER",        "KC Socratic Ladder",   "ladders",    "Ladder"),
    5: ("GEM-GLOSSARY",         "Glossary",             "entries",    "Glossary"),
    6: ("GEM-STORY",            "Story",                "stories",    "Story"),
}


_CHALLENGE_WORDS = [
    "Allah", "Rahman", "Karim", "Kitaab", "Qalam", "Sabar",
    "Mehnat", "Sachai", "Ustaad", "Taleem",
]


SLA_HOURS = {"URGENT": 24, "HIGH": 48, "MEDIUM": 120, "LOW": 240}
