"""Ingest DeepSeek grading output and store it in the database."""
import json
import zipfile
from datetime import date, timedelta
from decimal import Decimal
from pathlib import Path as _Path

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.db import transaction
from django.utils import timezone

from exams.models import Student, Exam, Submission, Attendance, DailyTask, ModelQuestion, RPSItem
from exams.services.bkt import BKTParams, update
from exams.pdf import save_student_report_pdf
from exams.parsing import (extract_json, coerce_score, coerce_confidence,
                           normalize_mistakes, normalize_tasks,
                           normalize_students)

ALLOWED_TOP_LEVEL_KEYS = {
    "exam", "parent_summary", "students", "absent", "warnings",
}


def _safe_subject(value, model):
    """Truncate a subject string to the model's subject field max_length.
    Industry-standard defensive truncation (Postel's Law, RFC 761).
    """
    if not value:
        return ''
    try:
        max_len = model._meta.get_field('subject').max_length
    except Exception:
        max_len = 50
    return str(value)[:max_len]


class Command(BaseCommand):
    help = "Ingest DeepSeek grading output JSON, store in DB, generate PDFs + ZIP"

    def add_arguments(self, parser):
        parser.add_argument("json_file", type=str)
        parser.add_argument("--quiet", action="store_true")
        parser.add_argument("--pdf", action="store_true")

    def handle(self, *args, **options):
        path = options["json_file"]
        quiet = options["quiet"]
        skip_pdf = not options["pdf"]

        try:
            with open(path, encoding="utf-8") as f:
                raw = f.read()
        except FileNotFoundError:
            raise CommandError("File not found: " + path)
        try:
            data = extract_json(raw)
        except ValueError as e:
            raise CommandError("Invalid JSON in " + path + ": " + str(e))

        # CANARY CHECK (runs only after successful parse)
        warnings_list = data.get('warnings', [])
        if not any('IDEALOGY-CANARY-9988' in str(w) for w in warnings_list):
            warnings_list.insert(0, '⚠️ SECURITY ALERT: PROMPT TAMPERED OR MANUALLY EDITED!')
            data['warnings'] = warnings_list
            # Add a warning to every question so the teacher sees it
            for s_data in data.get('students', []):
                for q in s_data.get('questions', []):
                    q['logical_analysis'] = 'SECURITY FLAG: ' + str(q.get('logical_analysis', ''))
                    q['knowledge_gap'] = 'Tampered JSON detected.'

        test_mode = data.get('test_mode', 'INDIVIDUAL') if isinstance(data, dict) else 'INDIVIDUAL'
        if test_mode not in ('INDIVIDUAL', 'DAILY_QUOTA'):
            test_mode = 'INDIVIDUAL'
        if not quiet:
            self.stdout.write(f"  ✅ Test mode: {test_mode}")

        if not isinstance(data, dict):
            raise CommandError("Payload must be a JSON object, got: " + type(data).__name__)
            
        unknown = sorted(set(data.keys()) - ALLOWED_TOP_LEVEL_KEYS)
        if unknown:
            raise CommandError("Unknown top-level keys: " + ", ".join(unknown))
            
        exam_meta = data.get("exam") or {}
        students_data = data.get("students") or []
        absent_codes = data.get("absent") or []

        for key in ["subject", "question_text", "max_marks", "exam_date"]:
            if not exam_meta.get(key):
                raise CommandError("Missing required field in exam: " + key)

        exam_date = self._parse_date(exam_meta["exam_date"])
        max_marks = Decimal(str(exam_meta["max_marks"]))
        paper_code = (exam_meta.get("paper_code") or "").strip()

        normalized_students = normalize_students(students_data)
        parent_summary = data.get("parent_summary") or {}

        created = 0
        updated = 0
        failed = 0
        absent_count = 0
        students_for_pdf = {}
        affected_students = []

        with transaction.atomic():
            for entry in normalized_students:
                code = entry["code"]

                try:
                    student = Student.objects.get(code=code, is_active=True)
                except Student.DoesNotExist:
                    self.stderr.write("Student not found: " + code)
                    failed += 1
                    continue

                affected_students.append(student)
                questions = entry["questions"]
                student_items = []

                for q_idx, q in enumerate(questions, start=1):
                    q_subject = q["subject"] or exam_meta["subject"]
                    q_text = q["question_text"] or exam_meta["question_text"]
                    q_expected = q["expected_answer"] or exam_meta.get("expected_answer", "")
                    q_rubric = q["rubric"] or exam_meta.get("rubric", "")
                    mq = self._resolve_model_question(q, paper_code)
                    q_max = mq.marks if (mq and mq.marks) else (coerce_score(q["max_marks_raw"], None) or max_marks)
                    
                    if not mq:
                        from exams.models_day_mission import StudentDayMission
                        from exams.models import EngineState
                        engine = EngineState.objects.filter(id=1).first()
                        if engine and engine.has_started:
                            day_num = engine.get_current_day()
                            mission_entry = StudentDayMission.objects.filter(student=student, day_number=day_num, subject=_safe_subject(q_subject, StudentDayMission)).first()
                            if mission_entry:
                                mq = mission_entry.question
                    if not mq and q_text:
                        mq = ModelQuestion.objects.filter(question_text__iexact=q_text.strip()).first()

                    if not q.get("kc_code") and mq and mq.kc_code:
                        q["kc_code"] = mq.kc_code
                        
                    exam, _ = Exam.objects.update_or_create(
                        student=student,
                        exam_date=exam_date,
                        question_index=q_idx,
                        defaults={
                            "subject": _safe_subject(q_subject, Exam),
                            "topic": q["topic"] or exam_meta.get("topic", ""),
                            "question_text": q_text,
                            "expected_answer": q_expected,
                            "rubric": q_rubric,
                            "max_marks": q_max,
                            "kc_code": q.get("kc_code", ""),
                            "model_question": mq,
                        },
                    )

                    q_score = coerce_score(q["score_raw"], q_max)
                    q_conf = coerce_confidence(q["confidence_raw"])

                    sub_status = "graded"
                    sub_error = ""
                    try:
                        from exams.services.expert_panel import evaluate_panel
                        from types import SimpleNamespace
                        mock_task = SimpleNamespace(id=999, student=student, task_ref=paper_code, task_type="PAPER_GRADING")
                        panel_decision = evaluate_panel(mock_task, {"questions": [q]}, context={"book_prefix": paper_code})
                        if not panel_decision.passed:
                            self.stdout.write(self.style.WARNING(f"Panel FAILED for {student.code}"))
                    except Exception as e:
                        pass

                    submission, sub_created = Submission.objects.update_or_create(
                        exam=exam,
                        defaults={
                            "ocr_text": q["student_answer_transcribed"],
                            "ai_score": q_score,
                            "ai_confidence": q_conf,
                            "ai_rationale": q["logical_analysis"],
                            "ai_mistakes": normalize_mistakes(q.get("wrong_vs_correct") or q.get("mistakes_raw")),
                            "ai_recommendations": entry["next_day_tasks"],
                            "ai_raw": {
                                "next_day_tasks": entry["next_day_tasks"],
                                "mastery_check": entry["mastery_check"],
                                "overall_feedback": entry["overall_feedback"],
                                "root_cause": q["root_cause"],
                                "max_marks": float(q_max),
                                "score": float(q_score) if q_score else 0.0,
                                "concept_story": q.get("concept_story", ""),
                                "handwriting_analysis": q.get("handwriting_analysis", {}),
                                "socratic_ladder": q.get("socratic_ladder", []),
                                "band": q.get("band", ""),
                                "answer_source": q.get("answer_source", ""),
                                "wrong_vs_correct": q.get("wrong_vs_correct", []),
                                "expert_comment": q.get("expert_comment", {}),
                                "model_answer_with_story": q.get("model_answer_with_story", ""),
                                "framework_cited": q.get("framework_cited", ""),
                                "parent_summary": parent_summary,
                                "question_index": q_idx,
                            },
                            "status": sub_status,
                            "error_message": sub_error,
                        },
                    )

                    # --- START BKT UPDATE ---
                    try:
                        kc_code = q.get("kc_code") or exam.kc_code
                        if kc_code and student:
                            rps, _ = RPSItem.objects.get_or_create(
                                student=student,
                                kc_code=kc_code,
                                defaults={'model_question': mq, 'next_due_at': timezone.now()}
                            )
                            is_correct = (q_score is not None and q_max is not None and (float(q_score) / float(q_max) >= 0.80))
                            bkt_params = BKTParams()
                            new_prob = update(rps.mastery_probability, is_correct, bkt_params)
                            rps.mastery_probability = new_prob
                            rps.mastery_attempts += 1
                            
                            if rps.mastery_probability >= 0.99:
                                rps.mastery_state = 'GRADUATED'
                            elif rps.mastery_probability >= 0.80:
                                rps.mastery_state = 'REVIEWING'
                                
                            rps.save()
                            self.stdout.write(f"  [BKT] Updated {student.code}/{kc_code} to {new_prob:.2f} ({rps.mastery_state})")
                    except Exception as bkt_err:
                        self.stdout.write(self.style.WARNING(f"  [BKT] Failed: {bkt_err}"))
                    # --- END BKT UPDATE ---

                    # --- HANDWRITING AI BRIDGE ---
                    try:
                        hw_analysis = q.get("handwriting_analysis", {})
                        hw_score = hw_analysis.get("score")
                        if hw_score is not None and hw_score >= 3:
                            from academy.models import AcademyStudent
                            from discipline.models import ClassHomeworkRecord

                            acad_student = AcademyStudent.objects.filter(linked_code=student.code).first()
                            if not acad_student:
                                acad_student = AcademyStudent.objects.filter(code=student.code).first()
                            if not acad_student:
                                acad_student = AcademyStudent.objects.create(
                                    code=student.code,
                                    full_name=student.name,
                                    grade=int(student.student_class[0]) if student.student_class and student.student_class[0].isdigit() else 9,
                                    linked_code=student.code
                                )
                            if acad_student:
                                record, _ = ClassHomeworkRecord.objects.get_or_create(
                                    student=acad_student, date=exam_date, subject=""
                                )
                                subj_lower = str(q_subject).lower()
                                if "urdu" in subj_lower or "tarjumatul quran" in subj_lower:
                                    record.handwriting_done = True
                                elif "english" in subj_lower:
                                    record.handwriting_done = True
                                else:
                                    record.handwriting_done = True
                                    record.handwriting_done = True
                                record.save()
                                self.stdout.write(f"    ✍️ Handwriting Points Awarded to {student.code} (Score: {hw_score})")
                    except Exception as e:
                        self.stdout.write(self.style.WARNING(f"Handwriting Bridge Error for {student.code}: {e}"))
                    # --- END HANDWRITING AI BRIDGE ---

                    # ONLY UPDATE MIZAN IF NOT HANDWRITING
                    if "handwriting" not in str(q_subject).lower():
                        from exams.models import DailyQuestionCount
                        from exams.models_trophy import TrophyEvent
                        from exams.mizan_algorithm import recompute

                        pace = student.daily_question_count or 3
                        dqc, _ = DailyQuestionCount.objects.get_or_create(student=student, date=exam_date)
                        dqc.completed_count += 1  # FIXED: count attempts, not pace
                        dqc.save()

                        # --- 60% Rule & Late Recovery Logic ---
                        is_late = False
                        try:
                            from exams.models import EngineState
                            from exams.models_day_mission import StudentDayMission
                            from datetime import datetime, time as dtime
                            engine = EngineState.objects.filter(id=1).first()
                            if engine and engine.start_date and mq:
                                sdm = StudentDayMission.objects.filter(student=student, question_id=mq.id).first()
                                if sdm:
                                    deadline_date = engine.start_date + timedelta(days=sdm.day_number - 1)
                                    deadline = timezone.make_aware(datetime.combine(deadline_date, dtime(23, 59, 59)))
                                    if timezone.now() > deadline:
                                        is_late = True
                        except Exception:
                            pass

                        grade_pct = float(q_score) / float(q_max) if q_max else 0.0
                        
                        if grade_pct >= 0.6:
                            trophy_multiplier = pace if test_mode == 'DAILY_QUOTA' else 1
                            if is_late:
                                trophy_multiplier *= 2
                            
                            event_key = f"Q_COMPLETE:{student.id}:{exam.id}:{q_idx}"
                            if not TrophyEvent.objects.filter(event_key=event_key).exists():
                                TrophyEvent.objects.create(
                                    student=student, event_key=event_key, date=exam_date,
                                    reason="QUESTION_COMPLETE", pace=pace,
                                    base_count=trophy_multiplier,
                                    bonus_count=0, count=trophy_multiplier,
                                    source_dqc_id=dqc.id,
                                )
                        # Persist test_mode on the exam for audit
                        try:
                            if exam.test_mode != test_mode:
                                exam.test_mode = test_mode
                                exam.save(update_fields=["test_mode"])
                        except Exception:
                            pass
                        try:
                            recompute(student)
                        except Exception:
                            pass

                        # FSRS-3
                        try:
                            from exams.services.fsrs import process_review
                            from exams.models import KnowledgeComponent, KCCard

                            if exam.kc_code and q.get("band"):
                                kc_obj, _ = KnowledgeComponent.objects.get_or_create(code=q["kc_code"])
                                card, _ = KCCard.objects.get_or_create(student=student, kc=kc_obj)
                                band = q.get("band", "").lower()
                                rating = 3 if band in ['excellent', 'good'] else (2 if band == 'fair' else 1)
                                days_elapsed = 0
                                if card.last_review_at:
                                    days_elapsed = (timezone.now() - card.last_review_at).days
                                state_dict = {'state': card.state, 'difficulty': card.difficulty, 'stability': card.stability, 'reps': card.reps}
                                new_state = process_review(state_dict, rating=rating, days_elapsed=days_elapsed)
                                card.difficulty = new_state['difficulty']
                                card.stability = new_state['stability']
                                card.state = new_state['state']
                                card.reps = new_state['reps']
                                card.last_review_at = timezone.now()
                                card.next_due_at = new_state['next_due_at']
                                card.save()
                        except Exception:
                            pass

                    student_items.append((exam, submission))
                    if sub_created:
                        created += 1
                    else:
                        updated += 1

                if student_items:
                    students_for_pdf[student.code] = (student, student_items)

                Attendance.objects.update_or_create(
                    student=student, date=exam_date,
                    defaults={"present": True, "reason": ""},
                )

                for _task in entry["next_day_tasks"]:
                    if isinstance(_task, dict):
                        _cat = _task.get("category") or ""
                        _title = _task.get("title") or ""
                        task_desc = ((_cat + ": ") if _cat else "") + _title
                    else:
                        task_desc = str(_task)
                    DailyTask.objects.update_or_create(
                        student=student, date_assigned=exam_date,
                        date_due=exam_date + timedelta(days=1),
                        subject=_safe_subject(exam_meta["subject"], DailyTask), description=str(task_desc),
                        defaults={},
                    )

                if not quiet:
                    self.stdout.write("✅ " + code + " - " + student.name + ": " + str(len(questions)) + " questions received.")

            for code in absent_codes:
                code = (code or "").strip()
                if not code: continue
                try:
                    student = Student.objects.get(code=code, is_active=True)
                except Student.DoesNotExist:
                    failed += 1
                    continue
                Attendance.objects.update_or_create(
                    student=student, date=exam_date,
                    defaults={"present": False, "reason": "Test not submitted"},
                )
                absent_count += 1
                if not quiet:
                    self.stdout.write("  " + code + " - " + student.name + ": ABSENT")

        # --- AUTO-TRIGGER OVERDUE PENALTIES ---
        # After processing all students, apply overdue penalties for each one
        for s in affected_students:
            try:
                call_command('apply_overdue_penalties', student=s.code, verbosity=0)
                self.stdout.write(f"  ⚠️ Overdue penalties re-evaluated for {s.code}")
            except Exception as e:
                self.stdout.write(self.style.WARNING(f"  Overdue penalty error for {s.code}: {e}"))
        # --- END AUTO-TRIGGER ---

        zip_path = None
        pdf_count = 0
        if not skip_pdf and students_for_pdf:
            out_dir = _Path(settings.BASE_DIR).parent / "output" / "daily_reports"
            out_dir.mkdir(parents=True, exist_ok=True)
            zip_path = out_dir / ("idealogy_reports_" + str(exam_date) + ".zip")
            pdf_paths = []
            for code, (student, items) in students_for_pdf.items():
                try:
                    p = save_student_report_pdf(student, exam_date, items, out_dir=out_dir)
                    pdf_paths.append(p)
                    pdf_count += 1
                except Exception as e:
                    self.stderr.write("PDF failed for " + code + ": " + str(e))
            if pdf_paths:
                with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
                    for p in pdf_paths:
                        zf.write(p, arcname=p.name)

        accounted = set(students_for_pdf.keys())
        for _c in absent_codes:
            if _c: accounted.add(_c.strip())
        missing = Student.objects.filter(is_active=True).count() - len(accounted)
        if missing > 0:
            self.stdout.write(self.style.WARNING("⚠️ Note: " + str(missing) + " other active students were not in this payload."))
        self.stdout.write("")
        self.stdout.write(self.style.SUCCESS(f"Created: {created}, Updated: {updated}, Absent: {absent_count}, Failed: {failed}"))
        if pdf_count:
            self.stdout.write(self.style.SUCCESS("PDFs generated: " + str(pdf_count)))

    def _resolve_model_question(self, q, paper_code):
        slug = (q.get("model_question_slug") or "").strip()
        if not slug: return None
        qs = ModelQuestion.objects.filter(question_slug=slug)
        if paper_code: qs = qs.filter(paper__code=paper_code)
        return qs.first()

    def _parse_date(self, s):
        if isinstance(s, date): return s
        try:
            return date.fromisoformat(s)
        except (ValueError, TypeError):
            raise CommandError("exam_date must be YYYY-MM-DD, got: " + str(s))
