"""
scripts/seed_school_data.py
===========================
Populates Rapha-Bethel BNPS with real data extracted from the official school flyers.

Run from the project root:
    python manage.py shell < scripts/seed_school_data.py
  or:
    python manage.py runscript seed_school_data   (if django-extensions installed)

Safe to run multiple times — uses get_or_create throughout.
"""

import os, sys, django
# Allow running directly: python scripts/seed_school_data.py
if __name__ == '__main__':
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
    django.setup()

from decimal import Decimal
from django.contrib.auth import get_user_model
from core.models import School
from finance.models import FeeStructure
from academics.models import SchoolClass

User = get_user_model()
YEAR = '2025-2026'

print('\n' + '='*60)
print('  Rapha-Bethel BNPS — Data Seed Script')
print('='*60)

# ─────────────────────────────────────────────────────────────
# 1. SCHOOL PROFILE
# ─────────────────────────────────────────────────────────────
print('\n[1] Updating school profile...')

school, _ = School.objects.get_or_create(id=1)
school.name              = 'Rapha-Bethel Bilingual Nursery and Primary School'
school.code              = 'RAPHA-BETHEL'
school.address           = 'Rue des Pavés avant EEC, Feu Rouge Bessengue'
school.city              = 'Douala'
school.quarter           = 'Bessengue'
school.phone             = '+237 670 177 979'
school.email             = 'raphabethel4u@gmail.com'
school.website           = 'https://raphabethel.org/BNPS'
school.academic_year     = YEAR
school.current_term      = 1
school.is_bilingual      = True
school.default_language  = 'both'
school.motto             = 'Work · Morality · Success'
school.save()
print(f'   ✔ School profile updated: {school.name}')

# ─────────────────────────────────────────────────────────────
# 2. FEE STRUCTURES
# ─────────────────────────────────────────────────────────────
# From the flyers:
#
# NURSERY (Maternelle):
#   Instalment 1 (Oct 10):  60 000 XAF
#   Instalment 2 (Feb 10):  40 000 XAF
#   Instalment 3 (Apr 10):  10 000 XAF
#   TOTAL:                 110 000 XAF
#
# CLASS 1 to 5 (SIL au CM2):
#   Instalment 1 (Oct 10):  50 000 XAF
#   Instalment 2 (Feb 10):  40 000 XAF
#   Instalment 3 (Apr 10):  10 000 XAF
#   TOTAL:                 100 000 XAF
#
# CLASS 6 (CM2 in French system):
#   Instalment 1 (Oct 10):  85 000 XAF
#   Instalment 2 (Feb 10):  40 000 XAF
#   Instalment 3 (Apr 10):  20 000 XAF
#   TOTAL:                 145 000 XAF
#
# OTHER FEES (all classes):
#   Registration — New pupils:    15 000 XAF (once)
#   Registration — Old pupils:    10 000 XAF (once)
#   Extra classes 1st & 2nd term: 15 000 XAF (termly)
#   Extra classes 3rd term:       10 000 XAF (termly)
#   Report card:                   1 000 XAF (termly)
#   Exam fee CM2:              To be decided
# ─────────────────────────────────────────────────────────────

print('\n[2] Creating fee structures...')

# Get the CM2 class object for the Class 6 specific fee
cm2_class = SchoolClass.objects.filter(level='class6').first()

# Admin user for created_by (use first superuser)
admin_user = User.objects.filter(is_superuser=True).first()

fees = [
    # ── NURSERY TUITION ──────────────────────────────────────
    dict(
        name='Nursery Tuition — Term 1',
        name_fr='Frais de scolarité Maternelle — 1er Trimestre',
        fee_type='tuition',
        amount=Decimal('60000'),
        payment_frequency='termly',
        class_level='nursery',
        term=1,
        is_mandatory=True,
        description='1st instalment due 10 October',
        description_fr='1ère tranche due le 10 Octobre',
    ),
    dict(
        name='Nursery Tuition — Term 2',
        name_fr='Frais de scolarité Maternelle — 2ème Trimestre',
        fee_type='tuition',
        amount=Decimal('40000'),
        payment_frequency='termly',
        class_level='nursery',
        term=2,
        is_mandatory=True,
        description='2nd instalment due 10 February',
        description_fr='2ème tranche due le 10 Février',
    ),
    dict(
        name='Nursery Tuition — Term 3',
        name_fr='Frais de scolarité Maternelle — 3ème Trimestre',
        fee_type='tuition',
        amount=Decimal('10000'),
        payment_frequency='termly',
        class_level='nursery',
        term=3,
        is_mandatory=True,
        description='3rd instalment due 10 April',
        description_fr='3ème tranche due le 10 Avril',
    ),

    # ── PRIMARY CLASS 1–5 TUITION ────────────────────────────
    dict(
        name='Primary (Class 1–5) Tuition — Term 1',
        name_fr='Frais de scolarité Primaire (SIL–CM2) — 1er Trimestre',
        fee_type='tuition',
        amount=Decimal('50000'),
        payment_frequency='termly',
        class_level='primary',
        term=1,
        is_mandatory=True,
        description='1st instalment due 10 October. Covers SIL, CP, CE1, CE2, CM1, CM2, Class 1–5.',
        description_fr='1ère tranche due le 10 Octobre.',
    ),
    dict(
        name='Primary (Class 1–5) Tuition — Term 2',
        name_fr='Frais de scolarité Primaire (SIL–CM2) — 2ème Trimestre',
        fee_type='tuition',
        amount=Decimal('40000'),
        payment_frequency='termly',
        class_level='primary',
        term=2,
        is_mandatory=True,
        description='2nd instalment due 10 February.',
        description_fr='2ème tranche due le 10 Février.',
    ),
    dict(
        name='Primary (Class 1–5) Tuition — Term 3',
        name_fr='Frais de scolarité Primaire (SIL–CM2) — 3ème Trimestre',
        fee_type='tuition',
        amount=Decimal('10000'),
        payment_frequency='termly',
        class_level='primary',
        term=3,
        is_mandatory=True,
        description='3rd instalment due 10 April.',
        description_fr='3ème tranche due le 10 Avril.',
    ),

    # ── CLASS 6 / CM2 TUITION ────────────────────────────────
    dict(
        name='Class 6 Tuition — Term 1',
        name_fr='Frais de scolarité Classe 6 — 1er Trimestre',
        fee_type='tuition',
        amount=Decimal('85000'),
        payment_frequency='termly',
        class_level='specific',
        term=1,
        is_mandatory=True,
        description='1st instalment due 10 October. Class 6 only.',
        description_fr='1ère tranche due le 10 Octobre. Classe 6 uniquement.',
    ),
    dict(
        name='Class 6 Tuition — Term 2',
        name_fr='Frais de scolarité Classe 6 — 2ème Trimestre',
        fee_type='tuition',
        amount=Decimal('40000'),
        payment_frequency='termly',
        class_level='specific',
        term=2,
        is_mandatory=True,
        description='2nd instalment due 10 February. Class 6 only.',
        description_fr='2ème tranche due le 10 Février. Classe 6 uniquement.',
    ),
    dict(
        name='Class 6 Tuition — Term 3',
        name_fr='Frais de scolarité Classe 6 — 3ème Trimestre',
        fee_type='tuition',
        amount=Decimal('20000'),
        payment_frequency='termly',
        class_level='specific',
        term=3,
        is_mandatory=True,
        description='3rd instalment due 10 April. Class 6 only.',
        description_fr='3ème tranche due le 10 Avril. Classe 6 uniquement.',
    ),

    # ── REGISTRATION ─────────────────────────────────────────
    dict(
        name='Registration Fee — New Pupils',
        name_fr='Frais d\'inscription — Nouveaux élèves',
        fee_type='registration',
        amount=Decimal('15000'),
        payment_frequency='once',
        class_level='all',
        term=1,
        is_mandatory=True,
        description='One-time registration for new pupils. Due at enrollment.',
        description_fr='Inscription unique pour les nouveaux élèves.',
    ),
    dict(
        name='Registration Fee — Returning Pupils',
        name_fr='Frais d\'inscription — Anciens élèves',
        fee_type='registration',
        amount=Decimal('10000'),
        payment_frequency='once',
        class_level='all',
        term=1,
        is_mandatory=True,
        description='Re-registration for returning pupils. Due at start of year.',
        description_fr='Réinscription pour les anciens élèves.',
    ),

    # ── EXTRA CLASSES ─────────────────────────────────────────
    dict(
        name='Extra Classes — Term 1 & 2',
        name_fr='Cours supplémentaires — 1er & 2ème Trimestre',
        fee_type='activity',
        amount=Decimal('15000'),
        payment_frequency='termly',
        class_level='all',
        term=1,
        is_mandatory=False,
        description='Supplementary classes on campus. 15 000 XAF per term for Terms 1 and 2.',
        description_fr='Cours supplémentaires sur le campus.',
    ),
    dict(
        name='Extra Classes — Term 3',
        name_fr='Cours supplémentaires — 3ème Trimestre',
        fee_type='activity',
        amount=Decimal('10000'),
        payment_frequency='termly',
        class_level='all',
        term=3,
        is_mandatory=False,
        description='Supplementary classes on campus. 10 000 XAF for Term 3.',
        description_fr='Cours supplémentaires — 3ème trimestre.',
    ),

    # ── REPORT CARD ───────────────────────────────────────────
    dict(
        name='Report Card Fee',
        name_fr='Frais de bulletin',
        fee_type='other',
        amount=Decimal('1000'),
        payment_frequency='termly',
        class_level='all',
        term=1,
        is_mandatory=True,
        description='Report card production fee — 1 000 XAF per term.',
        description_fr='Frais d\'édition du bulletin — 1 000 XAF par trimestre.',
    ),
]

created_count = 0
updated_count = 0

for fee_data in fees:
    # Separate specific_classes handling
    specific_classes = []
    if fee_data.get('class_level') == 'specific' and cm2_class:
        specific_classes = [cm2_class]

    obj, created = FeeStructure.objects.get_or_create(
        name=fee_data['name'],
        academic_year=YEAR,
        defaults={
            'name_fr':           fee_data.get('name_fr', ''),
            'fee_type':          fee_data['fee_type'],
            'amount':            fee_data['amount'],
            'payment_frequency': fee_data['payment_frequency'],
            'class_level':       fee_data.get('class_level', 'all'),
            'term':              fee_data.get('term', 1),
            'is_mandatory':      fee_data.get('is_mandatory', True),
            'description':       fee_data.get('description', ''),
            'description_fr':    fee_data.get('description_fr', ''),
            'is_active':         True,
            'created_by':        admin_user,
        }
    )

    if specific_classes:
        obj.specific_classes.set(specific_classes)

    if created:
        created_count += 1
        print(f'   + Created: {obj.name} — {obj.amount:,.0f} XAF')
    else:
        updated_count += 1
        print(f'   ~ Exists:  {obj.name}')

print(f'\n   Fee structures: {created_count} created, {updated_count} already existed.')

# ─────────────────────────────────────────────────────────────
# 3. SUMMARY
# ─────────────────────────────────────────────────────────────
print('\n' + '='*60)
print('  SEED COMPLETE')
print('='*60)
print(f'''
School Profile:  {school.name}
Address:         {school.address}
Phone:           {school.phone}
Email:           {school.email}
Academic Year:   {school.academic_year}

Fee Summary (2025-2026):
  Nursery total:       110 000 XAF  (60k + 40k + 10k)
  Class 1–5 total:     100 000 XAF  (50k + 40k + 10k)
  Class 6 total:       145 000 XAF  (85k + 40k + 20k)

  New pupil registration:      15 000 XAF
  Returning pupil registration: 10 000 XAF
  Extra classes (T1 & T2):     15 000 XAF/term
  Extra classes (T3):          10 000 XAF
  Report card:                  1 000 XAF/term

Payment accounts:
  AZZICUL:   N° 02-7215 (in name of child)
  CCA BANK:  10006-0024876980126

School hours:
  Nursery:   Mon–Thu  7:30–13:00,  Fri 7:30–12:00
  Primary:   Mon–Thu  7:30–14:30,  Fri 7:30–12:00
  Office:    Mon–Thu  7:30–15:30,  Fri 7:30–12:00
''')