"""Report reflection scores (SOLO taxonomy, Biggs and Collis).

Standards: DBI and MTSS progress monitoring; ISBE extended-response rubric.
"""
from django.core.management.base import BaseCommand
from django.db.models import Count, Avg

from exams.models import StoryReflection, ReflectionScore

SOLO_LABEL = {0: "Prestructural", 1: "Unistructural", 2: "Multistructural",
              3: "Relational", 4: "Extended abstract"}


class Command(BaseCommand):
    help = "Print reflection score summary (SOLO taxonomy)."

    def add_arguments(self, parser):
        parser.add_argument("--date", default="", help="Filter by teaching_date (YYYY-MM-DD)")
        parser.add_argument("--code", default="", help="Filter by student code, e.g. S-0017")

    def handle(self, *args, **options):
        qs = StoryReflection.objects.select_related("student", "story", "score")
        if options["date"]:
            qs = qs.filter(story__teaching_date=options["date"])
        if options["code"]:
            qs = qs.filter(student__code=options["code"])

        total = qs.count()
        scored = qs.filter(score__isnull=False).count()
        pending = total - scored
        self.stdout.write("Reflections: " + str(total)
                          + " | scored: " + str(scored)
                          + " | pending: " + str(pending))

        if not total:
            return

        if scored:
            avg = qs.filter(score__isnull=False).aggregate(a=Avg("score__solo_level"))["a"]
            self.stdout.write("Mean SOLO level: " + str(round(avg, 2)))

            dist = (qs.filter(score__isnull=False)
                    .values("score__solo_level")
                    .annotate(n=Count("id"))
                    .order_by("score__solo_level"))
            self.stdout.write("Distribution:")
            for row in dist:
                lvl = row["score__solo_level"]
                self.stdout.write("  " + str(lvl) + " "
                                  + SOLO_LABEL.get(lvl, "?") + ": " + str(row["n"]))

        by_student = (qs.values("student__code", "student__name")
                      .annotate(scored=Count("score"),
                                total=Count("id"))
                      .order_by("student__code"))
        self.stdout.write("")
        self.stdout.write("Per student:")
        for row in by_student:
            self.stdout.write("  " + row["student__code"] + " "
                              + (row["student__name"] or "")[:25].ljust(25)
                              + " scored " + str(row["scored"]) + "/" + str(row["total"]))
