"""kc_lock - freeze/unfreeze KC pipeline entities.

Design: design/KC-PIPELINE-FIREWALL-v1.0.md section 5.
Standards: NIST SP 800-53 AC-6, CM-3; ISO 27001 A.5.3, A.5.15, A.8.32;
ALCOA+ Original; 21 CFR 11.10(e); Rule 9; Rule 13 (HITL); Rule 28.

Usage:
  python manage.py kc_lock --unlock \\
      --scope ENTITY_INSTANCE --entity ModelQuestion --id 42 \\
      --reason "Correcting Q6 ... (40+ chars)" --duration 30

  python manage.py kc_lock --lock --scope GLOBAL
  python manage.py kc_lock --status
"""
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone as _tz

from exams.models import KcPipelineLock, CorrectionLog


VALID_SCOPES = {"GLOBAL", "ENTITY_TYPE", "ENTITY_INSTANCE"}
MIN_REASON_LEN = 40


class Command(BaseCommand):
    help = "Freeze/unfreeze KC pipeline entities. Reason >= 40 chars required for unlock."

    def add_arguments(self, parser):
        g = parser.add_mutually_exclusive_group(required=True)
        g.add_argument("--lock", action="store_true", help="Set lock.")
        g.add_argument("--unlock", action="store_true", help="Set unlock window.")
        g.add_argument("--status", action="store_true", help="Show current locks.")
        parser.add_argument("--scope", choices=sorted(VALID_SCOPES))
        parser.add_argument("--entity", help="Model name when scope != GLOBAL.")
        parser.add_argument("--id", type=int, help="Instance pk when scope=ENTITY_INSTANCE.")
        parser.add_argument("--reason", default="", help="Required >= 40 chars for unlock.")
        parser.add_argument("--duration", type=int, default=30,
                            help="Minutes until auto re-lock (default 30).")

    def handle(self, *args, **opts):
        if opts["status"]:
            return self._status()

        if opts["unlock"]:
            return self._unlock(opts)

        return self._lock(opts)

    # -------- status --------
    def _status(self):
        now = _tz.now()
        self.stdout.write("=== KcPipelineLock (active unlocks) ===")
        active = KcPipelineLock.objects.filter(locked=False)
        n = 0
        for lk in active:
            if lk.re_lock_at and lk.re_lock_at <= now:
                continue
            n += 1
            target = f"{lk.scope}:{lk.entity_type or '*'}:{lk.entity_id or '*'}"
            self.stdout.write(
                f"  #{lk.id} {target}  re_lock_at={lk.re_lock_at}  by={lk.unlocked_by}"
            )
        self.stdout.write(f"active unlocks: {n}")

    # -------- lock --------
    def _lock(self, opts):
        scope = opts.get("scope") or "GLOBAL"
        entity = opts.get("entity") or ""
        eid = opts.get("id")

        if scope == "GLOBAL":
            KcPipelineLock.objects.create(scope="GLOBAL", locked=True)
            # P14-12: a GLOBAL lock cancels every active unlock window
            # (Rule 10 - one source of truth; NIST AC-6).
            cancelled = (KcPipelineLock.objects
                         .filter(locked=False)
                         .update(locked=True, re_lock_at=_tz.now()))
            self._audit("lock", "GLOBAL", "", None,
                        f"manual re-lock; cancelled {cancelled} unlock window(s)")
        elif scope == "ENTITY_TYPE":
            if not entity:
                raise CommandError("--entity required for ENTITY_TYPE")
            KcPipelineLock.objects.create(scope="ENTITY_TYPE",
                                          entity_type=entity, locked=True)
            self._audit("lock", "ENTITY_TYPE", entity, None, "manual re-lock")
        else:
            if not entity or eid is None:
                raise CommandError("--entity and --id required for ENTITY_INSTANCE")
            KcPipelineLock.objects.create(scope="ENTITY_INSTANCE",
                                          entity_type=entity, entity_id=eid,
                                          locked=True)
            self._audit("lock", "ENTITY_INSTANCE", entity, eid, "manual re-lock")
        self.stdout.write(self.style.SUCCESS("Lock set."))

    # -------- unlock --------
    def _unlock(self, opts):
        scope = opts.get("scope")
        entity = opts.get("entity") or ""
        eid = opts.get("id")
        reason = (opts.get("reason") or "").strip()
        duration = opts.get("duration") or 30

        if scope not in VALID_SCOPES:
            raise CommandError(f"--scope must be one of {sorted(VALID_SCOPES)}")
        if len(reason) < MIN_REASON_LEN:
            raise CommandError(
                f"reason must be >= {MIN_REASON_LEN} chars (Rule 26 / NIST SI-10)."
            )
        if duration <= 0 or duration > 480:
            raise CommandError("duration must be 1..480 minutes.")

        if scope == "ENTITY_TYPE" and not entity:
            raise CommandError("--entity required for ENTITY_TYPE")
        if scope == "ENTITY_INSTANCE" and (not entity or eid is None):
            raise CommandError("--entity and --id required for ENTITY_INSTANCE")

        now = _tz.now()
        lock = KcPipelineLock.objects.create(
            scope=scope,
            entity_type=entity,
            entity_id=eid,
            locked=False,
            reason=reason,
            unlocked_at=now,
            re_lock_at=now + timedelta(minutes=duration),
        )
        CorrectionLog.objects.create(
            kind="FIREWALL",
            target_model=(entity or "*"),
            target_id=(eid or 0),
            field_name="<unlock>",
            reason=reason,
            actor_label="terminal:teacher",
        )
        self._audit("unlock", scope, entity, eid, reason, duration, lock.id)
        self.stdout.write(self.style.SUCCESS(
            f"Unlock window #{lock.id} opened for {duration} min; "
            f"auto re-lock at {lock.re_lock_at}."
        ))

    # -------- helpers --------
    def _audit(self, event, scope, entity, eid, reason, duration=0, lock_id=0):
        log = Path.home() / "idealogy" / "tmp" / "kc_firewall.jsonl"
        log.parent.mkdir(parents=True, exist_ok=True)
        entry = {
            "ts": datetime.now(timezone.utc).isoformat(),
            "event": event,
            "actor": "terminal:teacher",
            "scope": scope,
            "entity": entity,
            "entity_id": eid,
            "duration_min": duration,
            "lock_id": lock_id,
            "reason": reason,
        }
        with log.open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(entry) + "\n")
