"""Purge old SessionEvent and LoginAttempt rows (Section 11.7).

Retention: SessionEvent 90 days, LoginAttempt 30 days.
Audit-log every run (append-only). Standards: ISO 27001 A.8.10
(information deletion); ISO 27701 7.4.5 (deletion of personal data);
OWASP ASVS 5.0 (do not retain session data beyond need).
"""
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path as _Path

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

from exams.models import SessionEvent, LoginAttempt


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


class Command(BaseCommand):
    help = "Purge SessionEvent older than 90 days and LoginAttempt older than 30 days."

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

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

        s_qs = SessionEvent.objects.filter(ended_at__lt=s_cut)
        a_qs = LoginAttempt.objects.filter(created_at__lt=a_cut)
        s_n = s_qs.count()
        a_n = a_qs.count()

        if options["dry_run"]:
            self.stdout.write("Would purge: SessionEvent=" + str(s_n)
                              + " LoginAttempt=" + str(a_n))
            return

        s_qs.delete()
        a_qs.delete()

        record = {
            "when": now.isoformat(),
            "session_days": options["session_days"],
            "attempt_days": options["attempt_days"],
            "deleted_session_events": s_n,
            "deleted_login_attempts": a_n,
            "cutoffs": {
                "session_event_before": s_cut.isoformat(),
                "login_attempt_before": a_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(
            "Purged SessionEvent=" + str(s_n)
            + " LoginAttempt=" + str(a_n)))
