"""Purge StudentSession rows older than retention (default 7 days).

Retention: StudentSession 7 days (handoff pending #2, Session 23).
Standards: ISO 15489-1:2016 s9 (retention schedule); ISO 27001 A.8.10
(information deletion); ISO 27701 s7.4.5 (deletion of personal data);
NIST SP 800-63B-4 s7 (session lifecycle); OWASP ASVS 5.0.
"""
import json
from datetime import timedelta
from pathlib import Path as _Path

from django.core.management.base import BaseCommand
from django.db.models import Q
from django.utils import timezone as tz

from integrity.models import StudentSession


LOG_PATH = _Path("/home/orkoworo/idealogy/tmp/purge_student_sessions.jsonl")


class Command(BaseCommand):
    help = "Purge StudentSession rows older than --days (default 7)."

    def add_arguments(self, parser):
        parser.add_argument("--days", type=int, default=7)
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        now = tz.now()
        cut = now - timedelta(days=options["days"])

        # Two safe cases:
        #  (a) cleanly ended long ago
        #  (b) stale active row (crashed browser; never formally ended)
        qs = StudentSession.objects.filter(
            Q(is_active=False, ended_at__lt=cut)
            | Q(is_active=True, last_seen_at__lt=cut)
        )
        n = qs.count()

        if options["dry_run"]:
            self.stdout.write(
                f"Would purge: StudentSession={n} (cutoff={cut.isoformat()})"
            )
            return

        qs.delete()

        record = {
            "when": now.isoformat(),
            "days": options["days"],
            "deleted_student_sessions": n,
            "cutoff": cut.isoformat(),
        }
        try:
            LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
            with LOG_PATH.open("a", encoding="utf-8") as fh:
                fh.write(json.dumps(record) + "\n")
        except Exception as exc:
            self.stderr.write("Log write failed: " + str(exc))

        self.stdout.write(self.style.SUCCESS(
            f"Purged StudentSession={n}"
        ))
