"""
Seed the SCHOOL-DB permission catalog and the "Principal" role.

* Fills SchoolPermission with view/add/change/delete permissions for every
  admin-panel model, using the exact Django-style codenames the frontend
  already checks via hasPerm() (add_classfeestructure, change_exam, ...).
* Creates the "Principal" role and grants it every permission in the
  fee, attendance, announcements and reports (stats) categories.

Idempotent — safe to re-run.  Usage:
  .venv\\Scripts\\python.exe seed_principal_role.py
"""

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")

import django

django.setup()

from school_admin.models import (
    SchoolPermission,
    SchoolRole,
    SchoolRolePermission,
)

# category -> [(model codename suffix, human name)]
MODELS_BY_CATEGORY = {
    "students": [
        ("student", "Student"),
        ("studentsubject", "Student Subject"),
        ("studentsubjectgroup", "Student Subject Group"),
    ],
    "parents": [
        ("parent", "Parent"),
        ("studentparent", "Student-Parent Link"),
    ],
    "teachers": [
        ("teacher", "Teacher"),
        ("subjectteacher", "Subject Teacher Assignment"),
    ],
    "enrollments": [
        ("studentenrollment", "Student Enrollment"),
    ],
    "academics": [
        ("academicyear", "Academic Year"),
        ("academicterm", "Academic Term"),
        ("standard", "Standard"),
        ("section", "Section"),
        ("academicclass", "Academic Class"),
        ("classsubject", "Class Subject"),
        ("subject", "Subject"),
        ("subjectcategory", "Subject Category"),
        ("subjectgroup", "Subject Group"),
    ],
    "fee": [
        ("feecategory", "Fee Category"),
        ("feecomponent", "Fee Component"),
        ("classfeestructure", "Class Fee Structure"),
        ("studentfeeassignment", "Student Fee Assignment"),
        ("feecollection", "Fee Collection"),
    ],
    "announcements": [
        ("announcementtype", "Announcement Type"),
        ("classannouncement", "Class Announcement"),
        ("commonannouncement", "Common Announcement"),
        ("studentannouncement", "Student Announcement"),
        ("teacherannouncement", "Teacher Announcement"),
    ],
    "attendance": [
        ("attendancesession", "Attendance Session"),
        ("studentattendance", "Student Attendance"),
        ("attendanceleave", "Attendance Leave"),
    ],
    "timetable": [
        ("weekday", "Week Day"),
        ("timetable", "Timetable"),
    ],
    "tasks": [
        ("tasktype", "Task Type"),
    ],
    "exams": [
        ("examtype", "Exam Type"),
        ("exam", "Exam"),
        ("examsubject", "Exam Subject"),
    ],
    "transport": [
        ("transporttype", "Transport Type"),
        ("transportvehicle", "Transport Vehicle"),
        ("route", "Route"),
        ("stop", "Stop"),
        ("studenttransport", "Student Transport"),
        ("teachertransport", "Teacher Transport"),
    ],
    "payslips": [
        ("teacherpaystructure", "Teacher Pay Structure"),
        ("monthlypayslip", "Monthly Pay Slip"),
        ("paymenttransaction", "Payment Transaction"),
    ],
    "reports": [
        ("reports", "Reports & Statistics"),
        ("dashboard", "Dashboard"),
    ],
}

ACTIONS = [("view", "Can view"), ("add", "Can add"),
           ("change", "Can change"), ("delete", "Can delete")]

PRINCIPAL_CATEGORIES = {"fee", "attendance", "announcements", "reports"}

created_perms = 0
for category, models in MODELS_BY_CATEGORY.items():
    for suffix, label in models:
        for action, action_label in ACTIONS:
            codename = f"{action}_{suffix}"
            _, created = SchoolPermission.objects.get_or_create(
                codename=codename,
                defaults={
                    "name": f"{action_label} {label.lower()}",
                    "category": category,
                    "description": f"{action_label} {label}",
                },
            )
            if created:
                created_perms += 1

print(f"permissions created: {created_perms} (total {SchoolPermission.objects.count()})")

principal, created = SchoolRole.objects.get_or_create(
    name="Principal",
    defaults={
        "description": (
            "School principal — full access to fees, attendance, "
            "announcements and statistics/reports."
        ),
    },
)
print("Principal role:", "created" if created else "already exists", f"(id={principal.id})")

granted = 0
for perm in SchoolPermission.objects.filter(category__in=PRINCIPAL_CATEGORIES):
    _, created = SchoolRolePermission.objects.get_or_create(
        role=principal, permission=perm
    )
    if created:
        granted += 1
print(f"permissions granted to Principal: {granted} "
      f"(role now has {principal.role_permissions.count()})")
print("DONE")
