from .models import EngineState
from exams.decorators import require_delegation, require_teacher_or_delegation
import logging
from exams.models import StudentStarCommitment
"""API views for the exams app."""
import datetime
import io
import json
import uuid
from pathlib import Path as _Path

from django.contrib import messages
from django.contrib.auth.models import User
from django.core.management import call_command
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render, redirect, reverse
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.db import transaction
from django.urls import reverse_lazy
from rest_framework import viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from .models import Student, Exam, Submission, Attendance, DailyTask, ParentReport, WhatsAppLog, ReasoningStep
from .models import PortalFeatureLog  # 2026-11-09: pre-existing F821 fix
from .kc_firewall import _sanctioned_view
from .serializers import (
    StudentSerializer, ExamSerializer, SubmissionSerializer,
    AttendanceSerializer, DailyTaskSerializer, ParentReportSerializer,
    WhatsAppLogSerializer,
)





from .views_viewsets import (  # noqa: F401 — Strangler Fig facade (Handover V2 Phase 2)
    StudentViewSet,
    ExamViewSet,
    SubmissionViewSet,
    AttendanceViewSet,
    DailyTaskViewSet,
    ParentReportViewSet,
    WhatsAppLogViewSet,
)

from .views_health import (  # noqa: F401 — Strangler Fig facade (Handover V2 Phase 2)
    old_portal_health_redirect,
    old_parent_health_redirect,
    portal_admin_health_list,
    portal_admin_health_edit,
    portal_admin_mfa_enroll,
    portal_admin_mfa_challenge,
    portal_admin_health_proposals,
    portal_admin_health_proposals_approve,
    portal_admin_health_snapshots,
    portal_admin_health_snapshots_rollback,
    portal_teacher_health,
    portal_parent_health,
    portal_health_v2_test,
    portal_health,
)

from .views_teacher import (  # noqa: F401 — Strangler Fig facade (Handover V2 Phase 2)
    portal_teacher_hub,
    portal_teacher_ops,
    portal_teacher_lectures,
    portal_teacher_reflections,
    portal_teacher_live,
    portal_teacher_bulk,
    portal_teacher_guide,
    portal_teacher_peers,
    portal_teacher_sessions,
    portal_teacher_paste,
    portal_teacher_recall,
    portal_teacher_home,
    portal_teacher_build_cards,
    portal_teacher_workflow,
    portal_teacher_attendance,
    portal_teacher_safeguards,
    portal_teacher_messages,
    portal_teacher_pipelines,
    portal_teacher_support,
    portal_teacher_support_detail,
    portal_teacher_reassign,
    portal_teacher_assign_glossary,
    portal_teacher_violations,
    portal_teacher_stage_completions,
    portal_teacher_assign_books,
    portal_teacher_content,
    portal_teacher_add_kc,
    teacher_get_student_questions,
    portal_teacher_student_questions,
    portal_teacher_tasks,
    portal_teacher_live_data,
    portal_control_room,
    portal_teacher_ops_sitrep,
    portal_teacher_daily_codes,
)

from .views_student_portal import (  # noqa: F401
    portal_study,
    portal_lecture_request,
    portal_glossary,
    portal_terms,
    portal_profile,
    _profile_audience,
    portal_detail_step,
    portal_progress,
    portal_memorize,
    portal_submit_edit,
    portal_ai_flow_submit,
    portal_understand,
    portal_memorize_submit,
    _rank_term_match,
    portal_task_list,
    portal_task_detail,
    portal_task_submit,
    portal_task_pause,
    portal_task_funnel,
    _task_idempotency_key,
    _task_feature_key,
    _task_feature_enabled,
    portal_system_k_kaam_safar,
    portal_system_k_kaam_safar_detail,
    portal_my_todo,
    portal_dashboard,
    portal_full_leaderboard,
    portal_upload_center,
    portal_test_upload_guide,
    personal_todo_action,
    portal_my_duties,
    engine_status,
    engine_toggle,
    update_pacing,
)

from .views_content_pipeline import (  # noqa: F401
    portal_gem_chain,
    portal_gem_stage,
    _build_slots,
    _normalize_subject,
    _resolve_gem_prompt_path,
    _gem_tabs,
    _gem_stage_slots,
    _extract_system_prompt,
    portal_dohrai,
    portal_dohrai_attempt,
    portal_my_paper,
    portal_my_papers,
    portal_model_paper_submit,
    _extract_json_payload,
    _list_saved_batches,
    _saved_ns,
    book_members,
    book_handoff,
    book_recall,
    my_assignments,
    portal_stage_complete,
    _build_pipeline_data,
    portal_parent_messages,
    _student_or_parent,
    _sla_due_from,
    portal_parent_voice_task,
    portal_heartbeat,
    portal_guide_kzm,
    portal_acknowledgement,
    portal_my_results,
)

from .views_residual import (  # noqa: F401
    whoami,
    parent_portal,
    _build_faded_answer,
    portal_my_journey,
    get_coach_summary,
    _reasoning_state,
    portal_detail,
    portal_glossary_search,
    _advance_pipeline_legacy,
    old_pipeline_index_redirect,
    old_system_ka_kaam_safer_redirect,
    old_pipeline_detail_redirect,
    old_system_ka_kaam_safer_detail_redirect,
    portal_support_list,
    portal_support_new,
    portal_support_detail,
    portal_my_monster,
    portal_daily_review,
    portal_beta_legacy,
    portal_beta_certificate,
    portal_book_overview,
    save_points_matrix,
    send_shift_codes,
    mark_notification_read,
    safe_terminal,
    portal_public_leaderboard,
    portal_bulk_whatsapp,
    portal_public_leaderboard_global,
    portal_diary_upload,
    PortalLoginView,
    PortalLogoutView,
)




# ---------- Parent Portal (token-authenticated, read-only) ----------

from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
from rest_framework.permissions import AllowAny




# ---------- Portal login (Django session auth) ----------






















from .view_db_helpers import _current_student, _gate_state, _create_pipeline_task_for_stage, _teacher_assign, _advance_pipeline, _kc_subject_matches_student, _stage_all_done, _compute_question_assignments, _get_subject_options, _compute_effective_visibility, _user_has_feature, _filter_kc_refs_for_student, _is_student_user, _progress_for, _reflection_stats  # noqa: F401 — re-export (Handover V2 helper surgery)




from .view_helpers import _is_teacher, _paper_from_book, _compute_pipeline_status, STAGE_TO_TASK_TYPE, SAFEGUARD_FEATURES, PIPELINE_STAGES, _student_enrolled_subjects, _SUBJECT_TO_PREFIX, _no_student_redirect, _board_prediction, _band, SLA_HOURS, _CHALLENGE_WORDS, GEM_STAGES, _SUBJECT_FOLDERS  # noqa: F401 — re-export (Handover V2 helper surgery)













































# ---------------------------------------------------------------------------
# RPS Phase 5 - teacher oversight page (read-only)
# Design: design/RPS-DESIGN-v1.1.md Section 8.
# Standards: WCAG 2.2 AA; OWASP ASVS 4.1.1 (RBAC); Rule G (Roman Urdu);
#   Rule 10 (read-only - rps_select / rps_sync remain sole writers);
#   Section 15.4 (no daily teacher action required).
# ---------------------------------------------------------------------------


# ---------------------------------------------------------------------------
# Phase 3 - Student Task Queue views
# Design: design/PROP-2026-10-07-STUDENT-TASK-QUEUE-v3.1.md Sections 3, 5.
# Standards: Rule 10 (dispatch only, no writer fork); Rule 11 (prompt from
#   dispatcher, no invented text); Rule H (student content teacher_approved=False);
#   ISO 21500 4.3.3; GOV.UK Task List; WCAG 2.2 AA; Rule G; ACID submit.
# ---------------------------------------------------------------------------














# ---------------------------------------------------------------------------
# Phase 5 - Student Task Queue: teacher views
# Design: design/PROP-2026-10-07-STUDENT-TASK-QUEUE-v3.1.md Sections 5, 6.
# Standards: Rule 10 (dispatch only); Rule 11; Rule H; ISO 21500 4.3.3;
#   Womack & Jones Lean Thinking (auto-split); Fowler Feature Toggles;
#   ITIL 4 Release Management (toggle log); GOV.UK Task List; WCAG 2.2 AA;
#   Rule G; Section 15.4 (no teacher terminal commands per day).
# ---------------------------------------------------------------------------




# ---------------------------------------------------------------------------
# Task Pipeline - student view (9-stage vertical task list)
# Standards: GOV.UK Task List; Material Design Stepper (inner); WCAG 2.2 AA;
#   aria-current="step"; Rule G (Roman Urdu); Rule 10 (read-only view).
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Pipeline auto-chain (Cooper Stage-Gate; paper-owned; ISO 21500 4.3.3)
# ---------------------------------------------------------------------------




























# ---------------------------------------------------------------------------
# Teacher pipeline dashboard
# Standards: GOV.UK Task List; ITIL 4 Change Enablement; WCAG 2.2 AA;
#   Rule G; Rule 10 (view only).
# ---------------------------------------------------------------------------






# ---------------------------------------------------------------------------
# Rule 15.1 - Teacher-Parent messaging (500-char bounded channel)
# Standards: Rule 15; WCAG 2.2 SC 3.3.1; ISO 9241-110; ISO 27001 A.5.3;
#   ISO 27701 7.2.8; SAP Four-Eyes (only staff send, parents read)
# ---------------------------------------------------------------------------




# ---------------------------------------------------------------------------
# Rule 16 - Support Ticket System
# Standards: ISO 10002:2018; ITIL 4 Service Desk; ISO 9001 9.1.2, 10.2;
#   WCAG 2.2 AA; ISO 27001 A.5.3, A.5.15; ISO 27701 7.2.8; Rule 13 oversight.
# ---------------------------------------------------------------------------
















# ---------------------------------------------------------------------------
# Rule 17 - Idealogy Safeguards (per-user feature control)
# Standards: NIST AC-6; ISO 27001 A.5.15/A.5.18; OWASP A01:2021;
#   Martin Fowler Permission Toggle; Rule 17.
# ---------------------------------------------------------------------------
# Feature catalogue: every feature that can be per-user controlled.











# ---------------------------------------------------------------------------
# Health Centre views (added 2026-10-08, Phase 2.4b)
# Design: design/HEALTH-CENTRE-POLICY-v1.0.1.md
# Standards: Amazon AHR; EWS ABC; PBIS; Goss v. Lopez 1975;
#   WCAG 2.2 AA; Rule G (Roman Urdu); Rule 9; IN-22 (exit routes).
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
# Teacher health event logging (Phase 2.5, 2026-10-08)
# Standards: Amazon AHR; Rule 10 (via exams.health.apply_policy);
#   Rule 12 (Mizan); Rule 13 (HITL — teacher is the actor);
#   EU AI Act Art. 14; ISO 27001 A.8.15; Rule G.
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Parent health view (Phase 2.6, 2026-10-08)
# Standards: FERPA (parent access to their own child only);
#   Rule 14 (parent scope); Rule 15 (AI-readable profile constraints);
#   Amazon AHR (dashboard shape); WCAG 2.2 AA; Rule G; IN-22.
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Funnel view (Phase 3.2a, 2026-10-08)
# Design: design/GAMIFICATION-SPEC-v1.0.md
# Standards: Baymard checkout; GOV.UK Task List; Nielsen NN #1, NN #3;
#   WCAG 2.2 SC 2.4.8 (location), 2.4.7 (focus), 3.3.2 (labels);
#   ISO 9241-110 (self-descriptiveness); Rule 10 (writes via exams.quests);
#   Rule 12 (Mizan); Rule 13 (HITL via teacher reset); IN-22 (exit route).
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Phase 7.6 — Admin Console: Health Centre metric list
# Design: design/ADMIN-CONSOLE-SPEC-v1.0.md §9 (Screen 1)
# Standards: ISO 9241-110; Nielsen 2006 (progressive disclosure);
#   WCAG 2.2 AA; Rule 17 (feature toggle gating); Rule G (Roman Urdu);
#   Rule 13 (HITL teacher role); IN-26.
# Feature toggle: admin_console (default OFF).
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Phase 7.6.3c — Admin console: metric edit form
# Design: design/ADMIN-CONSOLE-SPEC-v1.0.md §9 (Screen 2)
# Standards: ISO 9241-110; Nielsen 2006; WCAG 2.2 AA; Rule 17; Rule G;
#   Rule 13; Rule 9 (audit); IN-26.
# Feature toggle: admin_console.
# This view builds a ConfigChangeProposal — it does NOT apply changes.
# The maker-checker workflow (7.6.5) and 2FA (7.6.4) gate the apply step.
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Phase 7.6.4b — TOTP enrolment + step-up challenge
# Standards: RFC 6238; NIST SP 800-63B AAL2; OWASP ASVS V6.3 + V7.5.3;
#   ISO 27001 A.5.15; Rule 17; Rule G (Roman Urdu).
# ---------------------------------------------------------------------------





# ---------------------------------------------------------------------------
# Phase 7.6.5 + 7.6.6 UI: proposal approval + snapshot rollback
# Standards: Rule 10 (UI delegates to canonical commands); Rule 13 (four-eyes
# enforced by the command); Rule 17 (toggle-gated); Rule G (Roman Urdu);
# WCAG 2.2 AA; ISO 9241-110.
# ---------------------------------------------------------------------------







# ---------------------------------------------------------------------------
# Teacher Hub — one page, every link
# Standards: GOV.UK Service Manual (one-place-to-find); Nielsen NN #1;
#   ISO 9241-110 (self-descriptiveness); WCAG 2.2 AA; Rule G; Rule 10.
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
# Teacher Operations Center (TOC) — Phase 8.5
# Standards: ITIL 4 Event Management; ISO 9001:2015 9.1;
#   GOV.UK Service Manual; Google SRE Ch. 6; NIST SP 800-137.
# Rule-based, not AI-generated. Every fact cites a row.
# ---------------------------------------------------------------------------














# ---------------------------------------------------------------------------
# Parent voice-note task completion (Rule 15.2 anti-fraud)
# Standards: ISO/IEC 30107-3 (challenge-response liveness);
#   ISO 27001 A.5.15, A.8.15; ISO 27701 7.2.8; PECA 2016 s.3;
#   Rule 13 (four-eyes); Rule 15, Rule 22.
# ---------------------------------------------------------------------------
import secrets as _secrets





# ---------------------------------------------------------------------------
# Policy violation logging (Rule 12, Rule 22, Section 23.13 P-KZM-04)
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
# Stage completion request (Rule 13 HITL; NIST AC-6; COSO P3)
# ---------------------------------------------------------------------------





# ---------------------------------------------------------------------------
# Turn 14c-1 (2026-10-11) - Team-Lead Boss UI: invite helpers
# Standards: design/PIPELINE-TEAM-LEAD-MODEL-v1.1.md 3.1;
#   ITIL 4 Team Lead; Team Topologies; Rule 9 (log every change);
#   Rule 13 (delegation envelope); Rule 23; Rule 24; Rule 28.
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
# Turn 14c-2 (2026-10-11) - Team-Lead Boss UI: hand off a task
# Standards: design/PIPELINE-TEAM-LEAD-MODEL-v1.1.md 3.2;
#   Rule 13 (delegation envelope); Rule 25 (one task one owner);
#   Rule 9 (log first); Kleppmann DDIA Ch. 7 (atomic handoff);
#   Rule 23; Rule 24; Rule 28.
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
# Turn 14c-3 (2026-10-11) - Member view: my delegated tasks
# Standards: design/PIPELINE-TEAM-LEAD-MODEL-v1.1.md 3.3;
#   Rule 25 (read-only view); Rule 23; Rule 24; Rule 28.
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
# Turn 14c-4 (2026-10-11) - Boss recall: move a handed-off task back
# Standards: design/PIPELINE-TEAM-LEAD-MODEL-v1.1.md 3.4;
#   Rule 9 (append-only; TaskClaim preserved); Rule 25 (one owner);
#   Kleppmann DDIA Ch.7 (atomic); Rule 23; Rule 24; Rule 28.
# ---------------------------------------------------------------------------



# --- P21-6/P21-7: student model-paper submission ---
import re as _re
from pathlib import Path as _Path














# --- P27b: per-stage 18-slot page ---

























# ---------------------------------------------------------------------------
# DOHRAI-1 (2026-10-16) — Aaj ka Dohrai (student-facing RPS display)
# Standards: Cepeda 2006; Roediger-Karpicke 2006; Driskell 1992;
#   Keller 1968; Bloom 1968; WCAG 2.2 AA; ISO 9241-110 s6.2;
#   Rule G, Rule 10 (read-only over RPS*), Rule 24, Rule 28.
# ---------------------------------------------------------------------------
from datetime import date as _dohrai_date, timedelta as _dohrai_td




# ---------------------------------------------------------------------------
# DOHRAI-2 (2026-10-16) — interactive practice + self-report
# Standards: Roediger & Karpicke 2006; Cepeda 2006; Driskell 1992;
#   Keller 1968 PSI; Bloom 1968; AERA/APA/NCME 2014 Std 1.0;
#   OWASP ASVS V4.1.1 (deny-by-default IDOR), V5.1 (input validation);
#   WCAG 2.2 AA SC 1.4.1, 3.3.1, 3.3.3, 2.4.7, 4.1.3;
#   ISO 9241-110 s6.2; Rule G (Roman Urdu, lang=ur-Latn); Rule 9 (append-only);
#   Rule 10 (rps_advance is canonical); Rule 24; Rule 28.
# ---------------------------------------------------------------------------


# ---------------------------------------------------------------------------
# DOHRAI-3 (2026-10-16) — Mera Paper: student views own uploaded paper with
# book-matched answers.
# Standards: Roediger & Karpicke 2006 (retrieval practice); Cepeda 2006;
#   Keller 1968 PSI; Fellegi & Sunter 1969 (record linkage);
#   ISO 8000-110 (master data quality); AERA/APA/NCME 2014 Std 1.0;
#   OWASP ASVS V4.1.1 (deny-by-default IDOR); WCAG 2.2 AA;
#   ISO 9241-110 s6.2; Rule G (Roman Urdu), Rule 9 (append-only),
#   Rule 10 (read-only over solved bank), Rule 24, Rule 28.
# ---------------------------------------------------------------------------





















# Auto-generated Engine Views
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
import json

    

from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from exams.utils.pagination import paginate  # UI Rule L1
import json







# ===== Phase G: Teacher Daily Test Codes =====


















































