"""set_enrolled_subjects - declare Student.enrolled_subjects (canonical writer).

Standards: Rule 10 (one canonical writer per concept); AERA/APA/NCME 2014
Std 1.0 (construct declared, not derived); 1EdTech OneRoster 1.2 (enrollment
as a first-class entity); Rule 23 (dry-run default, explicit --apply);
Rule 24 (sandbox first); ISO 27001 A.8.15 (change log); Section 3.6 (verify
then log); Saltzer & Schroeder 1975 (empty = fail-safe deny).
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from exams.models import Student
import json, pathlib

VALID = {"MT","PH","CH","BI","EN","UR","IS","CS","TQ"}

def _parse_subjects(s):
    out = []
    for tok in (s or "").split(","):
        p = tok.strip().upper()
        if not p:
            continue
        if p not in VALID:
            raise CommandError("invalid prefix: " + p + " (valid: " + ",".join(sorted(VALID)) + ")")
        if p not in out:
            out.append(p)
    return sorted(out)

class Command(BaseCommand):
    help = "Declare Student.enrolled_subjects. Canonical writer. Dry-run default."

    def add_arguments(self, parser):
        parser.add_argument("--student", default=None)
        parser.add_argument("--subjects", default=None)
        parser.add_argument("--batch", default=None, help="JSON: [{code, subjects}, ...].")
        parser.add_argument("--apply", action="store_true")

    def handle(self, *args, **opts):
        code = (opts["student"] or "").strip().upper()
        subs_arg = opts["subjects"]
        batch = opts["batch"]
        apply = opts["apply"]

        if batch and (code or subs_arg is not None):
            raise CommandError("use --student/--subjects OR --batch, not both")
        if not batch and not (code and subs_arg is not None):
            raise CommandError("pass --student and --subjects, or --batch FILE")

        plan = []
        if batch:
            p = pathlib.Path(batch)
            if not p.exists():
                raise CommandError("batch file not found: " + batch)
            data = json.loads(p.read_text())
            if not isinstance(data, list):
                raise CommandError("batch file must be a JSON list")
            for row in data:
                c = (row.get("code") or "").strip().upper()
                if not c:
                    raise CommandError("batch row missing 'code'")
                s = Student.objects.filter(code=c).first()
                if not s:
                    raise CommandError("student not found: " + c)
                new = _parse_subjects(",".join(row.get("subjects") or []))
                plan.append((s, new, list(s.enrolled_subjects or [])))
        else:
            s = Student.objects.filter(code=code).first()
            if not s:
                raise CommandError("student not found: " + code)
            new = _parse_subjects(subs_arg)
            plan.append((s, new, list(s.enrolled_subjects or [])))

        self.stdout.write("=== plan (" + str(len(plan)) + " students) ===")
        changed = 0
        for s, new, old in plan:
            flag = "OK" if new == old else "CHANGE"
            if new != old:
                changed += 1
            self.stdout.write("  " + s.code + " " + flag + "  " + str(old) + " -> " + str(new))

        if not apply:
            self.stdout.write("(DRY RUN - nothing written; pass --apply to write)")
            return

        with transaction.atomic():
            for s, new, old in plan:
                if new != old:
                    s.enrolled_subjects = new
                    s.save(update_fields=["enrolled_subjects"])
        self.stdout.write("Applied: " + str(changed) + " students updated.")
