"""config_snapshot - take a ConfigSnapshot of the current metric state.
Standards: Rule 10 (one writer); ISO 27001 A.8.15; ISO/IEC 42001 7.5."""
import json
from hashlib import sha256
from django.core.management.base import BaseCommand
from django.db import transaction
from exams.models import ConfigMetric, ConfigSnapshot


def _state(m):
    return {"code": m.code, "title_ur": m.title_ur, "category": m.category,
            "kind": m.kind, "severity": m.severity, "points": m.points,
            "direction": m.direction, "strictness": m.strictness,
            "grace_days": m.grace_days, "standard_cited": m.standard_cited,
            "threshold_expr": m.threshold_expr, "is_active": m.is_active}


class Command(BaseCommand):
    help = "Take a ConfigSnapshot of the current metric state."
    def add_arguments(self, p):
        p.add_argument("--note", default="")
        p.add_argument("--dry-run", action="store_true")
    def handle(self, *a, **o):
        payload = [_state(m) for m in ConfigMetric.objects.order_by("code")]
        pj = json.dumps(payload, sort_keys=True, separators=(",", ":"))
        digest = sha256(pj.encode("utf-8")).hexdigest()
        last = ConfigSnapshot.objects.order_by("-version").first()
        nv = (last.version + 1) if last else 1
        if o["dry_run"]:
            self.stdout.write("DRY: would create v" + str(nv) + " ("
                              + str(len(payload)) + " metrics, sha "
                              + digest[:12] + ")")
            return
        with transaction.atomic():
            ConfigSnapshot.objects.filter(is_current=True).update(is_current=False)
            ConfigSnapshot.objects.create(
                version=nv, payload_json=payload, sha256=digest,
                prev_version=(last.version if last else None),
                is_current=True, note=(o["note"] or "manual snapshot"))
        self.stdout.write("Created snapshot v" + str(nv) + " (sha "
                          + digest[:12] + ", " + str(len(payload)) + " metrics)")
