"""Edit a student demographic. Logs every change to CorrectionLog."""
import json

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

from exams.models import Student, CorrectionLog


EDITABLE = ["name", "father_name", "whatsapp_student", "whatsapp_parent",
            "student_class", "tier", "shift", "notes", "is_active"]


def _stringify(v):
    if v is None:
        return ""
    if isinstance(v, bool):
        return "true" if v else "false"
    return str(v)


class Command(BaseCommand):
    help = "Edit a student demographic. Logs each change."

    def add_arguments(self, parser):
        parser.add_argument("code", type=str)
        parser.add_argument("--set", action="append", default=[],
                            help="field=value. Repeat for multiple fields.")
        parser.add_argument("--reason", type=str, default="",
                            help="Why this change is being made.")
        parser.add_argument("--actor", type=str, default="terminal:teacher")

    def handle(self, *args, **opts):
        code = opts["code"].strip()
        try:
            s = Student.objects.get(code=code)
        except Student.DoesNotExist:
            raise CommandError("Student not found: " + code)
        if opts["set"] and not opts["reason"]:
            raise CommandError("--reason is required when using --set.")
        if not opts["set"]:
            self._show(s)
            return
        changes = []
        for pair in opts["set"]:
            if "=" not in pair:
                raise CommandError("Bad --set: " + pair)
            field, value = pair.split("=", 1)
            field = field.strip()
            if field not in EDITABLE:
                raise CommandError("Field not editable: " + field + ". Allowed: " + ", ".join(EDITABLE))
            old = getattr(s, field)
            if field == "tier":
                value = int(value)
            elif field == "is_active":
                value = value.lower() in ("1", "true", "yes", "y")
            elif field == "notes":
                pass
            else:
                value = str(value)
            if _stringify(old) == _stringify(value):
                continue
            setattr(s, field, value)
            changes.append((field, old, value))
        if not changes:
            self.stdout.write("No changes (values identical).")
            return
        s.save()
        for field, old, new in changes:
            CorrectionLog.objects.create(
                kind="DEMO",
                target_model="Student",
                target_id=s.id,
                student=s,
                field_name=field,
                old_value=_stringify(old),
                new_value=_stringify(new),
                reason=opts["reason"],
                actor_label=opts["actor"],
            )
            self.stdout.write("  " + field + ": " + _stringify(old) + " -> " + _stringify(new))
        self.stdout.write(self.style.SUCCESS("Updated " + code + " (" + str(len(changes)) + " field(s))"))

    def _show(self, s):
        self.stdout.write("Student: " + s.code + " - " + s.name)
        for f in EDITABLE:
            self.stdout.write("  " + f + " = " + _stringify(getattr(s, f)))
