"""Print a student profile for one audience.

Audiences: teacher (all), parent (parent_visible only),
student (shareable_with_student only).

Standards: GDPR Art. 15 (subject access); FERPA 99.10 (parent
inspection); Section 10.4 of the takeover guide.
"""
from django.core.management.base import BaseCommand, CommandError

from exams.models import Student, StudentProfile, ProfileEntry, ProfileSummary


DOMAIN_LABEL = {"BIO": "Biological", "PSY": "Psychological",
                "SOC": "Social", "ACA": "Academic"}


class Command(BaseCommand):
    help = "Print a student profile filtered by audience."

    def add_arguments(self, parser):
        parser.add_argument("code", help="Student code, e.g. S-0017")
        parser.add_argument("--for", dest="audience", default="teacher",
                            choices=["teacher", "parent", "student"],
                            help="Audience (default teacher).")

    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"])

        audience = options["audience"]
        try:
            profile = StudentProfile.objects.get(student=student)
        except StudentProfile.DoesNotExist:
            self.stdout.write("No profile exists for " + student.code + ".")
            return

        entry_qs = ProfileEntry.objects.filter(profile=profile)
        if audience == "parent":
            entry_qs = entry_qs.filter(parent_visible=True)
        elif audience == "student":
            entry_qs = entry_qs.filter(shareable_with_student=True)
        entry_qs = entry_qs.order_by("-entry_date", "-created_at")

        self.stdout.write("=== Profile for " + student.name
                          + " (" + student.code + ") - audience: "
                          + audience + " ===")

        # Privacy (GDPR Art. 25; Section 10.4):
        # - teacher sees the stored summary (built from all entries).
        # - parent/student must NEVER see the teacher summary, because
        #   it may contain entries they are not allowed to see. Instead
        #   their summary is recomputed on the fly from the FILTERED set.
        if audience == "teacher":
            summary = profile.summaries.order_by("-generated_at").first()
            if summary:
                self.stdout.write("Summary generated: " + summary.generated_at.isoformat()
                                  + " | entries at generation: " + str(summary.entry_count))
                for d in ("BIO", "PSY", "SOC", "ACA"):
                    val = getattr(summary, {"BIO": "biological_summary",
                                            "PSY": "psychological_summary",
                                            "SOC": "social_summary",
                                            "ACA": "academic_summary"}[d])
                    if val:
                        self.stdout.write("")
                        self.stdout.write("--- " + DOMAIN_LABEL[d] + " ---")
                        self.stdout.write(val)
                if summary.action_plan:
                    self.stdout.write("")
                    self.stdout.write("--- Action plan ---")
                    self.stdout.write(summary.action_plan)
            else:
                self.stdout.write("No summary generated yet.")
        else:
            from exams.management.commands.regen_summaries import (
                _summarize_domain, _action_plan,
            )
            by_domain = {}
            for e in entry_qs:
                by_domain.setdefault(e.domain, []).append(e)
            self.stdout.write("Audience-filtered summary (computed live from "
                              "visible entries only).")
            for d in ("BIO", "PSY", "SOC", "ACA"):
                text = _summarize_domain(by_domain.get(d, []))
                if text:
                    self.stdout.write("")
                    self.stdout.write("--- " + DOMAIN_LABEL[d] + " ---")
                    self.stdout.write(text)
            plan = _action_plan(by_domain)
            if plan:
                self.stdout.write("")
                self.stdout.write("--- Action plan ---")
                self.stdout.write(plan)

        self.stdout.write("")
        self.stdout.write("--- Entries (" + str(entry_qs.count()) + ") ---")
        for e in entry_qs:
            flags = []
            if e.parent_visible:
                flags.append("P")
            if e.shareable_with_student:
                flags.append("S")
            tag = ("[" + "".join(flags) + "]") if flags else "[ ]"
            self.stdout.write(f"{e.entry_date.isoformat()} {e.domain} conf={e.confidence} {tag} {e.observed}")
