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

Standards: OWASP ASVS 5.0 3.5.1 (session visibility);
NIST SP 800-63B 7.1 (session limits); ITIL 4 Incident Management.
"""
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone

from exams.models import Student, SessionEvent


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

    def add_arguments(self, parser):
        parser.add_argument("code", help="Student code, e.g. S-0017")
        parser.add_argument("--include-ended", action="store_true",
                            help="Also show recently ended sessions.")

    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).order_by("-started_at")
        if not options["include_ended"]:
            qs = qs.filter(active=True)

        rows = list(qs)
        self.stdout.write("Sessions for " + student.code + " (" + student.name + ")")
        if not rows:
            self.stdout.write("  (none)")
            return

        now = timezone.now()
        for ev in rows:
            mins = int((now - ev.last_seen_at).total_seconds() // 60)
            if mins < 60:
                ago_h = str(mins) + "m"
            elif mins < 1440:
                ago_h = str(mins // 60) + "h"
            else:
                ago_h = str(mins // 1440) + "d"
            ended = "" if ev.active else " ended=" + (ev.ended_reason or "?")
            self.stdout.write(
                "  id={id:<5} user={user:<14} active={active} ip={ip:<16} last_seen={ago:<9}{ended}".format(
                    id=ev.id,
                    user=ev.user.username,
                    active=("Y" if ev.active else "N"),
                    ip=(ev.ip or "-"),
                    ago=ago_h + " ago",
                    ended=ended,
                )
            )
