"""Terminate active sessions for a student (Section 11).

Logs an incident-style kill with reason. Standards: OWASP ASVS 5.0
3.5.1; NIST SP 800-63B 7.1; ITIL 4 Incident Management (session kill
is a logged incident-response action); ISO 27001 A.8.15.
"""
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone

from exams.models import Student, SessionEvent


class Command(BaseCommand):
    help = "Terminate all active sessions for one student (by code)."

    def add_arguments(self, parser):
        parser.add_argument("code", help="Student code, e.g. S-0017")
        parser.add_argument("--reason", required=True,
                            help="Why these sessions are being terminated.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Show what would be killed; do not change DB.")

    def handle(self, *args, **options):
        try:
            student = Student.objects.get(code=options["code"], is_active=True)
        except Student.DoesNotExist:
            raise CommandError("No active student with code " + options["code"])

        users = [u for u in (student.student_user, student.parent_user) if u]
        qs = SessionEvent.objects.filter(user__in=users, active=True)
        n = qs.count()

        if options["dry_run"]:
            self.stdout.write("Would kill " + str(n) + " active session(s) for "
                              + student.code + " (" + student.name + ").")
            return

        now = timezone.now()
        updated = qs.update(
            active=False, ended_reason="teacher_kill", ended_at=now,
        )
        self.stdout.write(self.style.SUCCESS(
            "Killed " + str(updated) + " active session(s) for "
            + student.code + " (" + student.name + ")."
        ))
        self.stdout.write("Reason: " + options["reason"][:200])
