"""
Management command: seed_fee_structure
Usage:  python manage.py seed_fee_structure [--year 2025-2026]

Loads the official fee table into FeeStructure and SchoolItemPrice
so staff don't have to type them in manually.

Place this file at:
  finance/management/commands/seed_fee_structure.py
(create __init__.py files in management/ and commands/ if not present)
"""
from django.core.management.base import BaseCommand
from finance.models import FeeStructure, SchoolItemPrice


class Command(BaseCommand):
    help = "Seed the database with the official Anglo & Bilingual fee structure"

    def add_arguments(self, parser):
        parser.add_argument(
            '--year',
            default='2025-2026',
            help='Academic year to seed, e.g. 2025-2026 (default: 2025-2026)',
        )

    def handle(self, *args, **options):
        year = options['year']

        self.stdout.write(self.style.MIGRATE_HEADING(
            f"\n📋 Seeding fee structure for {year} …\n"
        ))

        # ── Fee Structures ─────────────────────────────────────────────────
        defaults_list = FeeStructure.get_defaults()
        created_count = 0

        for data in defaults_list:
            obj, created = FeeStructure.objects.update_or_create(
                section=data['section'],
                class_group=data['class_group'],
                academic_year=year,
                defaults={
                    'registration_new':  data['registration_new'],
                    'registration_old':  data['registration_old'],
                    'total_fees':        data['total_fees'],
                    'installment_1':     data['installment_1'],
                    'installment_2':     data['installment_2'],
                    'is_active':         True,
                },
            )
            label = "✅ Created" if created else "🔄 Updated"
            self.stdout.write(f"  {label}: {obj}")
            if created:
                created_count += 1

        self.stdout.write("")

        # ── School Item Prices ─────────────────────────────────────────────
        item_defaults = SchoolItemPrice.get_defaults()
        item_created = 0

        for data in item_defaults:
            obj, created = SchoolItemPrice.objects.update_or_create(
                item_type=data['item_type'],
                academic_year=year,
                defaults={
                    'name':      data['name'],
                    'price':     data['price'],
                    'is_active': True,
                },
            )
            label = "✅ Created" if created else "🔄 Updated"
            self.stdout.write(f"  {label}: {obj}")
            if created:
                item_created += 1

        self.stdout.write(self.style.SUCCESS(
            f"\n🎉 Done! "
            f"{created_count} fee structure(s) and {item_created} item price(s) created.\n"
        ))