#!/usr/bin/env python3
"""
fix_class6_fees.py
==================
One-time script — sets class_level='class6' on all fee structures
that currently have class_level='specific' and are linked to Class 6,
OR that have no specific_classes linked (broken migration state).

Run on DEV first:
    python fix_class6_fees.py --settings=backend.settings

Then on production:
    OPENBLAS_NUM_THREADS=1 python fix_class6_fees.py --settings=backend.settings_production
"""

import os, sys, argparse
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument('--settings', default='backend.settings_production')
parser.add_argument('--dry-run', action='store_true')
args = parser.parse_args()

sys.path.insert(0, str(Path(__file__).resolve().parent))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', args.settings)
os.environ.setdefault('OPENBLAS_NUM_THREADS', '1')

import django
django.setup()

from finance.models import FeeStructure
from academics.models import SchoolClass

DRY = args.dry_run
if DRY:
    print("DRY RUN — no changes written\n")

# Find the Class 6 SchoolClass object
class6 = SchoolClass.objects.filter(level='class6').first()
if not class6:
    # Try by name/code
    class6 = SchoolClass.objects.filter(
        name__icontains='class 6'
    ).first() or SchoolClass.objects.filter(code__icontains='CL6').first()

print(f"Class 6 object: {class6} (level={class6.level if class6 else 'NOT FOUND'})\n")

# Show all fee structures to understand current state
print("ALL ACTIVE MANDATORY FEE STRUCTURES:")
print(f"{'ID':<5} {'NAME':<45} {'class_level':<12} {'specific_classes'}")
print("-" * 90)

fees = FeeStructure.objects.filter(is_active=True).order_by('class_level', 'name')
for f in fees:
    linked = list(f.specific_classes.values_list('name', flat=True))
    print(f"  {f.pk:<4} {f.name[:44]:<45} {f.class_level:<12} {linked or '—'}")

print()

# Find fees that should be class6:
# 1. class_level='specific' with Class 6 in specific_classes
# 2. class_level='specific' with NO specific_classes (broken — likely Class 6 fees)
to_fix = []

for f in FeeStructure.objects.filter(is_active=True, is_mandatory=True):
    linked = list(f.specific_classes.all())
    if f.class_level == 'specific':
        if class6 and class6 in linked:
            to_fix.append((f, 'specific → class6 (was linked to Class 6)'))
        elif not linked:
            to_fix.append((f, 'specific → class6 (no specific_classes — broken migration)'))

print(f"\nFees to fix ({len(to_fix)}):")
for f, reason in to_fix:
    print(f"  [{f.pk}] {f.name} — {reason}")

if not to_fix:
    print("  Nothing to fix! Fees may already be correct.")
    print("\n  If Class 6 invoices still don't generate, check that:")
    print("  1. FeeStructure.class_level choices include 'class6'")
    print("  2. finance_views.py has the class6 branch in _fee_applies_to_student")
    sys.exit(0)

if DRY:
    print("\nDry run complete — run without --dry-run to apply.")
    sys.exit(0)

confirm = input("\nApply fixes? (yes/no): ").strip().lower()
if confirm != 'yes':
    print("Aborted.")
    sys.exit(0)

fixed = 0
for f, reason in to_fix:
    f.class_level = 'class6'
    f.save(update_fields=['class_level'])
    print(f"  Fixed: {f.name}")
    fixed += 1

print(f"\nDone. {fixed} fee structures updated to class_level='class6'.")
print("Class 6 students should now get invoices in bulk generation.")
