"""Regenerate a profile summary from all ProfileEntry rows.

Append-only: writes a NEW ProfileSummary row each run. Never edits prior rows.

Standards: Section 10.5 (summary regenerated, not authored);
AERA/APA/NCME 2014 Std 13.7 (deterministic); NIST AI RMF MEASURE 2.6.
"""
from django.core.management.base import BaseCommand, CommandError

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


DOMAIN_TO_FIELD = {
    "BIO": "biological_summary",
    "PSY": "psychological_summary",
    "SOC": "social_summary",
    "ACA": "academic_summary",
}

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

MIN_ENTRIES_PER_DOMAIN = 3


def _summarize_domain(entries):
    if not entries:
        return ""
    n = len(entries)
    conf = [e.confidence for e in entries if e.confidence]
    avg = round(sum(conf) / len(conf), 1) if conf else None
    dates = sorted({e.entry_date for e in entries})
    dlo, dhi = dates[0].isoformat(), dates[-1].isoformat()
    parts = [f"{n} observation(s) between {dlo} and {dhi}."]
    if avg is not None:
        parts.append(f"Mean confidence: {avg}/5.")
    recent = sorted(entries, key=lambda e: (e.entry_date, e.created_at), reverse=True)[:3]
    for e in recent:
        snippet = e.observed.strip().replace("\\n", " ")
        if len(snippet) > 160:
            snippet = snippet[:157] + "..."
        parts.append(f"[{e.entry_date.isoformat()}] {snippet}")
    return " ".join(parts)


def _action_plan(by_domain):
    lines = []
    for d, label in DOMAIN_LABEL.items():
        n = len(by_domain.get(d, []))
        if n == 0:
            lines.append(f"Collect first {label} observation.")
        elif n < MIN_ENTRIES_PER_DOMAIN:
            lines.append(f"{label}: {n} observation(s). Add at least "
                         f"{MIN_ENTRIES_PER_DOMAIN - n} more.")
    if not lines:
        lines.append("All four BPS domains have baseline coverage. Continue observing.")
    return " ".join(lines)


class Command(BaseCommand):
    help = "Regenerate a ProfileSummary (append-only, deterministic)."

    def add_arguments(self, parser):
        parser.add_argument("code", nargs="?", default="",
                            help="Student code, e.g. S-0017. Use --all for every student.")
        parser.add_argument("--all", action="store_true",
                            help="Regenerate summaries for every StudentProfile.")

    def handle(self, *args, **options):
        if options["all"]:
            profiles = list(StudentProfile.objects.all())
            if not profiles:
                raise CommandError("No StudentProfile rows exist.")
        else:
            code = options["code"]
            if not code:
                raise CommandError("Provide a student code, or use --all.")
            try:
                student = Student.objects.get(code=code, is_active=True)
            except Student.DoesNotExist:
                raise CommandError("No active student with code " + code)
            profile, _ = StudentProfile.objects.get_or_create(student=student)
            profiles = [profile]

        created = 0
        for profile in profiles:
            entries = list(ProfileEntry.objects.filter(profile=profile))
            by_domain = {}
            for e in entries:
                by_domain.setdefault(e.domain, []).append(e)

            kwargs = {"profile": profile, "entry_count": len(entries)}
            for d, field in DOMAIN_TO_FIELD.items():
                kwargs[field] = _summarize_domain(by_domain.get(d, []))
            kwargs["action_plan"] = _action_plan(by_domain)

            summary = ProfileSummary.objects.create(**kwargs)
            created += 1
            self.stdout.write("  " + profile.student.code
                              + " | entries=" + str(len(entries))
                              + " | summary_id=" + str(summary.id)
                              + " | generated=" + summary.generated_at.isoformat())

        self.stdout.write(self.style.SUCCESS("Summaries created: " + str(created)))
