"""kernel_unfreeze - refresh the manifest and turn the freeze off.

Turn B (2026-10-11). Companion: design/PIPELINE-FIREWALL-v1.0.md

Steps:
  1. Compute current md5 of every frozen file.
  2. (Turn C will run tests here; currently warns and continues.)
  3. Write a new manifest version.
  4. Flip pipeline_freeze to False.
  5. Log to PortalFeatureLog.

Standards: ITIL 4 Change Enablement; ISO 27001 A.8.32;
ISO/IEC/IEEE 29119-3 5.4; Rule 9; Rule 10.
"""
import hashlib
import json
from pathlib import Path
from datetime import datetime, timezone

from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "Update the manifest and disable pipeline_freeze."

    def add_arguments(self, parser):
        parser.add_argument("--reason", required=True)
        parser.add_argument("--dry-run", action="store_true")
        parser.add_argument("--skip-tests", action="store_true",
                            help="Skip the frozen test suite (initial use only).")

    def handle(self, *args, **opts):
        reason = (opts["reason"] or "").strip()
        if len(reason) < 10:
            raise CommandError("--reason must be at least 10 characters")

        api_dir = Path(__file__).resolve().parent.parent.parent.parent
        manifest_path = api_dir.parent / "kernel_manifest.json"
        if not manifest_path.exists():
            raise CommandError("kernel_manifest.json not found")

        # ---- 1. Run tests (deferred to Turn C) ----
        if not opts.get("skip_tests"):
            try:
                from django.core.management import call_command
                self.stdout.write("running frozen test suite...")
                call_command("test", "exams.tests.test_kernel_invariants",
                             verbosity=0)
                self.stdout.write("tests PASSED")
            except Exception as e:
                raise CommandError(
                    "frozen tests failed; refusing to unfreeze: " + str(e)[:200])

        # ---- 2. Compute current md5s ----
        manifest = json.loads(manifest_path.read_text())
        frozen = manifest.get("frozen") or {}
        now = datetime.now(timezone.utc).isoformat()
        new_frozen = {}
        for rel in frozen.keys():
            p = api_dir / rel
            if p.exists():
                new_frozen[rel] = hashlib.md5(p.read_bytes()).hexdigest()
            else:
                new_frozen[rel] = "MISSING"

        new_manifest = dict(manifest)
        new_manifest["version"] = int(manifest.get("version", 0)) + 1
        new_manifest["released_at"] = now
        new_manifest["reason"] = reason[:200]
        new_manifest["frozen"] = new_frozen

        if opts.get("dry_run"):
            self.stdout.write("dry-run: would write manifest version "
                              + str(new_manifest["version"]))
            return

        manifest_path.write_text(json.dumps(new_manifest, indent=2))
        self.stdout.write("manifest updated to version "
                          + str(new_manifest["version"]))

        # ---- 3. Flip the flag ----
        from exams.models import PortalFeature, PortalFeatureLog
        f = PortalFeature.objects.filter(key="pipeline_freeze").first()
        if f is None:
            PortalFeature.objects.create(
                key="pipeline_freeze", enabled=False, note=reason[:200])
            self.stdout.write("created PortalFeature pipeline_freeze=False")
        elif f.enabled:
            f.enabled = False
            f.save(update_fields=["enabled", "updated_at"])
            self.stdout.write("pipeline_freeze set to False")
        else:
            self.stdout.write("already unfrozen")

        PortalFeatureLog.objects.create(
            key="pipeline_freeze.OFF",
            old_enabled=True, new_enabled=False, changed_by=None,
            note="unfreeze reason=" + reason[:200]
                 + " version=" + str(new_manifest["version"]))
        self.stdout.write("audit: pipeline_freeze.OFF logged")
