"""Add one anecdotal profile entry (append-only).

Standards: anecdotal record methodology (ERIC ED135174);
BPS three-domain model (Section 10.2);
GDPR Art. 16; FERPA 99.20; WIA-EDU-010 v2.0.
"""
import re
from datetime import date as _date

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from exams.models import Student, StudentProfile, ProfileEntry


BANNED_WORDS = [
    "lazy", "rude", "stupid", "dumb", "idiot", "useless",
    "weak", "bad", "hopeless", "good-for-nothing", "shameless",
    "naughty", "worthless", "foolish",
]


def _validate_observed(text):
    errors = []
    if not text or len(text.strip()) < 5:
        errors.append("observed too short")
    if len(text) > 4000:
        errors.append("observed too long (max 4000)")
    low = " " + text.lower() + " "
    found = [w for w in BANNED_WORDS if re.search(r"\b" + re.escape(w) + r"\b", low)]
    if found:
        errors.append("banned interpretive words: " + ", ".join(found))
    return errors


class Command(BaseCommand):
    help = "Add one ProfileEntry (append-only). Creates StudentProfile on first use."

    def add_arguments(self, parser):
        parser.add_argument("code", help="Student code, e.g. S-0017")
        parser.add_argument("--domain", required=True, choices=["BIO", "PSY", "SOC", "ACA"])
        parser.add_argument("--observed", required=True,
                            help="Concrete observed event. No interpretation, no adjectives.")
        parser.add_argument("--context", default="", help="Where, when, with whom.")
        parser.add_argument("--source", default="T", choices=["T", "P", "S"])
        parser.add_argument("--confidence", type=int, default=3,
                            help="1 low - 5 high. Default 3.")
        parser.add_argument("--date", default="", help="Entry date YYYY-MM-DD (default today).")
        parser.add_argument("--parent-visible", action="store_true",
                            help="Allow parent to see this entry.")
        parser.add_argument("--shareable", action="store_true",
                            help="Share this entry with the student.")

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

        conf = options["confidence"]
        if conf < 1 or conf > 5:
            raise CommandError("confidence must be 1-5, got " + str(conf))

        observed = (options["observed"] or "").strip()
        errs = _validate_observed(observed)
        if errs:
            raise CommandError("Validation failed: " + "; ".join(errs))

        entry_date = options["date"] or _date.today().isoformat()
        try:
            ed = _date.fromisoformat(entry_date)
        except ValueError:
            raise CommandError("Invalid date: " + entry_date)

        with transaction.atomic():
            profile, _created = StudentProfile.objects.get_or_create(student=student)
            entry = ProfileEntry.objects.create(
                profile=profile,
                entry_date=ed,
                domain=options["domain"],
                observed=observed,
                context=(options["context"] or "").strip(),
                source=options["source"],
                confidence=conf,
                parent_visible=bool(options["parent_visible"]),
                shareable_with_student=bool(options["shareable"]),
            )

        self.stdout.write(self.style.SUCCESS(
            "Added ProfileEntry id=" + str(entry.id)
            + " | " + student.code
            + " | " + options["domain"]
            + " | " + ed.isoformat()
            + " | parent_visible=" + str(entry.parent_visible)
            + " | shareable=" + str(entry.shareable_with_student)))
