import datetime
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.utils import timezone
from admissions.models import Program, Application, Enrollment
from profiles.models import StudentProfile, TeacherProfile
from communications.models import Notification
from courses.models import Course
from timetable.models import TimetableEntry
from payments.models import Payment
from certificates.models import Certificate
from website.models import Testimonial
from content.models import CourseMaterial, Quiz, QuizQuestion, QuizChoice

User = get_user_model()


class Command(BaseCommand):
    help = 'Seed the database with sample data for development and testing'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear',
            action='store_true',
            help='Clear existing seed data before seeding',
        )

    def handle(self, *args, **options):
        if options['clear']:
            self._clear()

        self.stdout.write('Creating superuser...')
        self._seed_superuser()

        self.stdout.write('Seeding programs...')
        programs = self._seed_programs()

        self.stdout.write('Seeding courses...')
        self._seed_courses(programs)

        self.stdout.write('Seeding teachers...')
        self._seed_teachers(programs)

        self.stdout.write('Seeding applications and students...')
        enrollments = self._seed_applications(programs)

        self.stdout.write('Seeding timetable entries...')
        self._seed_timetable(programs)

        self.stdout.write('Seeding payments...')
        self._seed_payments(enrollments)

        self.stdout.write('Seeding certificates...')
        self._seed_certificates(enrollments)

        self.stdout.write('Seeding testimonials...')
        self._seed_testimonials(programs)

        self.stdout.write('Seeding course content and quizzes...')
        self._seed_content()

        self.stdout.write(self.style.SUCCESS(
            '\nSeed complete!\n'
            '  Superuser:    admin@mlsfoundationug.org / Admin@2024!\n'
            '  Teachers:     teacher.ssemakula / teacher.nakato  (Teacher@2024!)\n'
            '  Students:     patricia.namutebi@gmail.com / samuel.wasswa@gmail.com  (Student@2024!)\n'
        ))

    # ------------------------------------------------------------------
    # Superuser
    # ------------------------------------------------------------------

    def _seed_superuser(self):
        email = 'admin@mlsfoundationug.org'
        if not User.objects.filter(email=email).exists():
            user = User.objects.create_superuser(
                username='admin',
                email=email,
                first_name='MLS',
                last_name='Admin',
                password='Admin@2024!',
            )
            user.role = User.SUPER_ADMIN
            user.is_verified = True
            user.save(update_fields=['role', 'is_verified'])
            self.stdout.write(f'  [Created] admin@mlsfoundationug.org (superuser)')
        else:
            self.stdout.write(f'  [Exists ] admin@mlsfoundationug.org')

    # ------------------------------------------------------------------
    # Programs
    # ------------------------------------------------------------------

    def _seed_programs(self):
        data = [
            {
                'name': 'Electrical Installation',
                'level': Program.NATIONAL_CERT,
                'duration': '2 Years',
                'tuition_fee': 400000,
                'practical_fee': 150000,
                'assessment_fee': 80000,
                'entry_requirement': 'UCE (O-Level) or equivalent',
                'description': 'Practical training in domestic and industrial electrical installation, wiring, and safety standards.',
            },
            {
                'name': 'Carpentry & Joinery',
                'level': Program.NATIONAL_CERT,
                'duration': '2 Years',
                'tuition_fee': 400000,
                'practical_fee': 150000,
                'assessment_fee': 80000,
                'entry_requirement': 'UCE (O-Level) or equivalent',
                'description': 'Furniture making, wood joinery, door and window fitting, and finishing techniques.',
            },
            {
                'name': 'Tailoring & Fashion Design',
                'level': Program.JUNIOR_CERT,
                'duration': '3 Years',
                'tuition_fee': 250000,
                'practical_fee': 100000,
                'assessment_fee': 50000,
                'entry_requirement': 'PLE or equivalent',
                'description': 'Garment construction, pattern making, fashion design, and textile techniques.',
            },
            {
                'name': 'Welding & Metal Fabrication',
                'level': Program.JUNIOR_CERT,
                'duration': '3 Years',
                'tuition_fee': 250000,
                'practical_fee': 100000,
                'assessment_fee': 50000,
                'entry_requirement': 'PLE or equivalent',
                'description': 'Arc welding, MIG/TIG welding, metal cutting, and fabrication of structures.',
            },
            {
                'name': 'Plumbing & Pipe Fitting',
                'level': Program.NATIONAL_CERT,
                'duration': '2 Years',
                'tuition_fee': 400000,
                'practical_fee': 150000,
                'assessment_fee': 80000,
                'entry_requirement': 'UCE (O-Level) or equivalent',
                'description': 'Water supply systems, sanitation, drainage, and pipe installation.',
            },
            {
                'name': 'Motor Vehicle Mechanics',
                'level': Program.DIPLOMA,
                'duration': '2 Years',
                'tuition_fee': 800000,
                'practical_fee': 250000,
                'assessment_fee': 150000,
                'entry_requirement': 'UACE (A-Level) or equivalent',
                'description': 'Engine overhaul, vehicle diagnostics, transmission systems, and auto-electrical.',
            },
            {
                'name': 'Fashion Design & Garment Technology',
                'level': Program.DIPLOMA,
                'duration': '2 Years',
                'tuition_fee': 800000,
                'practical_fee': 250000,
                'assessment_fee': 150000,
                'entry_requirement': 'UACE (A-Level) or equivalent',
                'description': 'Advanced fashion design, entrepreneurship in fashion, and garment production management.',
            },
            {
                'name': 'ICT / Computer Studies',
                'level': Program.NATIONAL_CERT,
                'duration': '2 Years',
                'tuition_fee': 400000,
                'practical_fee': 150000,
                'assessment_fee': 80000,
                'entry_requirement': 'UCE (O-Level) or equivalent',
                'description': 'Computer hardware, software applications, internet skills, and basic programming.',
            },
            {
                'name': 'Entrepreneurship & Business Skills',
                'level': Program.JUNIOR_CERT,
                'duration': '3 Years',
                'tuition_fee': 250000,
                'practical_fee': 100000,
                'assessment_fee': 50000,
                'entry_requirement': 'PLE or equivalent',
                'description': 'Business planning, financial literacy, marketing, and small enterprise management.',
            },
        ]

        programs = {}
        for item in data:
            prog, created = Program.objects.get_or_create(
                name=item['name'],
                level=item['level'],
                defaults=item,
            )
            programs[item['name']] = prog
            status = 'Created' if created else 'Exists '
            self.stdout.write(f'  [{status}] {prog.name}')
        return programs

    # ------------------------------------------------------------------
    # Courses
    # ------------------------------------------------------------------

    def _seed_courses(self, programs):
        curriculum = {
            'Electrical Installation': {
                1: [
                    ('Basic Electrical Theory', 'EI-101'),
                    ('DC Circuits & Components', 'EI-102'),
                    ('Electrical Safety & Regulations', 'EI-103'),
                    ('Tools, Equipment & Materials', 'EI-104'),
                ],
                2: [
                    ('AC Circuits & Systems', 'EI-201'),
                    ('Domestic Electrical Installation', 'EI-202'),
                    ('Industrial Wiring & Control', 'EI-203'),
                    ('Electrical Maintenance & Fault Finding', 'EI-204'),
                ],
            },
            'Carpentry & Joinery': {
                1: [
                    ('Timber Technology & Selection', 'CJ-101'),
                    ('Basic Joinery Techniques', 'CJ-102'),
                    ('Hand Tools & Workshop Safety', 'CJ-103'),
                    ('Technical Drawing for Carpentry', 'CJ-104'),
                ],
                2: [
                    ('Furniture Making & Design', 'CJ-201'),
                    ('Door & Window Fitting', 'CJ-202'),
                    ('Surface Finishing & Polishing', 'CJ-203'),
                    ('Entrepreneurship in Carpentry', 'CJ-204'),
                ],
            },
            'Tailoring & Fashion Design': {
                1: [
                    ('Introduction to Tailoring', 'TF-101'),
                    ('Basic Sewing Techniques', 'TF-102'),
                    ('Fabric Knowledge & Selection', 'TF-103'),
                    ('Measurements & Cutting', 'TF-104'),
                ],
                2: [
                    ('Pattern Making', 'TF-201'),
                    ('Garment Construction', 'TF-202'),
                    ('Fashion Illustration & Drawing', 'TF-203'),
                ],
                3: [
                    ('Advanced Tailoring & Draping', 'TF-301'),
                    ('Fashion Business & Marketing', 'TF-302'),
                    ('Final Project & Runway Preparation', 'TF-303'),
                ],
            },
            'Plumbing & Pipe Fitting': {
                1: [
                    ('Introduction to Plumbing', 'PP-101'),
                    ('Pipe Materials, Fittings & Joints', 'PP-102'),
                    ('Water Supply Systems', 'PP-103'),
                    ('Plumbing Tools & Safety', 'PP-104'),
                ],
                2: [
                    ('Sanitation & Sewerage Systems', 'PP-201'),
                    ('Drainage Installation', 'PP-202'),
                    ('Plumbing Maintenance & Repair', 'PP-203'),
                    ('Project Estimation & Management', 'PP-204'),
                ],
            },
            'Motor Vehicle Mechanics': {
                1: [
                    ('Automotive Technology Fundamentals', 'MV-101'),
                    ('Engine Systems & Components', 'MV-102'),
                    ('Transmission & Drive Train', 'MV-103'),
                    ('Auto-Electrical Basics', 'MV-104'),
                ],
                2: [
                    ('Vehicle Diagnostics & Scanning', 'MV-201'),
                    ('Fuel & Cooling Systems', 'MV-202'),
                    ('Braking & Suspension Systems', 'MV-203'),
                    ('Workshop Management & Business', 'MV-204'),
                ],
            },
            'ICT / Computer Studies': {
                1: [
                    ('Computer Fundamentals', 'ICT-101'),
                    ('MS Office Applications', 'ICT-102'),
                    ('Internet, Email & Online Safety', 'ICT-103'),
                    ('Computer Hardware & Maintenance', 'ICT-104'),
                ],
                2: [
                    ('Networking Fundamentals', 'ICT-201'),
                    ('Software Installation & Support', 'ICT-202'),
                    ('Data Management & Spreadsheets', 'ICT-203'),
                    ('ICT for Business & Entrepreneurship', 'ICT-204'),
                ],
            },
        }

        for prog_name, years in curriculum.items():
            prog = programs.get(prog_name)
            if not prog:
                continue
            for year_num, subjects in years.items():
                for name, code in subjects:
                    course, created = Course.objects.get_or_create(
                        program=prog,
                        code=code,
                        defaults={'name': name, 'year': year_num, 'is_active': True},
                    )
                    if created:
                        self.stdout.write(f'  [Created] {code} — {name}')

    # ------------------------------------------------------------------
    # Teachers (with program assignments)
    # ------------------------------------------------------------------

    def _seed_teachers(self, programs):
        teachers = [
            {
                'username': 'teacher.ssemakula',
                'email': 'j.ssemakula@mlsfoundationug.org',
                'first_name': 'John',
                'last_name': 'Ssemakula',
                'phone': '+256701234567',
                'profile': {
                    'specialization': 'Electrical Installation',
                    'qualification': 'B.Sc. Electrical Engineering, Makerere University',
                    'bio': 'Over 8 years of experience in electrical installation training and industry practice.',
                },
                'programs': ['Electrical Installation', 'Plumbing & Pipe Fitting'],
            },
            {
                'username': 'teacher.nakato',
                'email': 'g.nakato@mlsfoundationug.org',
                'first_name': 'Grace',
                'last_name': 'Nakato',
                'phone': '+256772345678',
                'profile': {
                    'specialization': 'Tailoring & Fashion Design',
                    'qualification': 'Diploma in Fashion & Garment Technology, Uganda Technical College',
                    'bio': 'Passionate about empowering women through practical fashion skills.',
                },
                'programs': ['Tailoring & Fashion Design'],
            },
        ]

        for t in teachers:
            user, created = User.objects.get_or_create(
                username=t['username'],
                defaults={
                    'email': t['email'],
                    'first_name': t['first_name'],
                    'last_name': t['last_name'],
                    'phone': t['phone'],
                    'role': User.TEACHER,
                    'is_verified': True,
                },
            )
            if created:
                user.set_password('Teacher@2024!')
                user.save()
                profile = TeacherProfile.objects.create(user=user, **t['profile'])
            else:
                profile, _ = TeacherProfile.objects.get_or_create(user=user)

            assigned = [programs[n] for n in t['programs'] if n in programs]
            profile.programs.set(assigned)
            status = 'Created' if created else 'Exists '
            self.stdout.write(f'  [{status}] {user.get_full_name()} -> {", ".join(t["programs"])}')

    # ------------------------------------------------------------------
    # Applications & Students
    # ------------------------------------------------------------------

    def _seed_applications(self, programs):
        elec = programs.get('Electrical Installation')
        tailoring = programs.get('Tailoring & Fashion Design')
        carpentry = programs.get('Carpentry & Joinery')
        mechanics = programs.get('Motor Vehicle Mechanics')

        app_data = [
            {
                'first_name': 'Derrick', 'last_name': 'Mugisha', 'other_names': 'Brian',
                'date_of_birth': '2002-04-15', 'gender': 'male', 'nationality': 'Ugandan',
                'national_id': 'CM92004150001F', 'phone_number': '+256780123456',
                'email': 'derrick.mugisha@gmail.com',
                'physical_address': 'Namugongo, Wakiso', 'district': 'Wakiso',
                'program_applied': elec,
                'highest_education_level': 'o_level',
                'last_school_attended': 'Mengo Senior School', 'year_of_completion': 2021,
                'emergency_contact_name': 'Sarah Mugisha',
                'emergency_contact_relationship': 'parent',
                'emergency_contact_phone': '+256704567890', 'emergency_contact_email': '',
                'status': Application.PENDING,
            },
            {
                'first_name': 'Aisha', 'last_name': 'Namukasa', 'other_names': '',
                'date_of_birth': '2003-09-20', 'gender': 'female', 'nationality': 'Ugandan',
                'national_id': '', 'phone_number': '+256755234567',
                'email': 'aisha.namukasa@yahoo.com',
                'physical_address': 'Ntinda, Kampala', 'district': 'Kampala',
                'program_applied': tailoring,
                'highest_education_level': 'primary',
                'last_school_attended': "St. Mary's Primary School", 'year_of_completion': 2019,
                'emergency_contact_name': 'Hassan Namukasa',
                'emergency_contact_relationship': 'parent',
                'emergency_contact_phone': '+256712345678', 'emergency_contact_email': '',
                'status': Application.PENDING,
            },
            {
                'first_name': 'Ronald', 'last_name': 'Kiggundu', 'other_names': 'Peter',
                'date_of_birth': '2000-01-10', 'gender': 'male', 'nationality': 'Ugandan',
                'national_id': 'CM92000100002M', 'phone_number': '+256701122334',
                'email': 'ronald.kiggundu@gmail.com',
                'physical_address': 'Bwaise, Kampala', 'district': 'Kampala',
                'program_applied': carpentry,
                'highest_education_level': 'o_level',
                'last_school_attended': 'Kampala High School', 'year_of_completion': 2018,
                'emergency_contact_name': 'Jane Kiggundu',
                'emergency_contact_relationship': 'parent',
                'emergency_contact_phone': '+256789012345', 'emergency_contact_email': '',
                'status': Application.UNDER_REVIEW,
            },
            {
                'first_name': 'Patricia', 'last_name': 'Namutebi', 'other_names': '',
                'date_of_birth': '1999-06-05', 'gender': 'female', 'nationality': 'Ugandan',
                'national_id': 'CF91999060001P', 'phone_number': '+256778899001',
                'email': 'patricia.namutebi@gmail.com',
                'physical_address': 'Kira, Wakiso', 'district': 'Wakiso',
                'program_applied': tailoring,
                'highest_education_level': 'o_level',
                'last_school_attended': "Kawempe Girls' School", 'year_of_completion': 2017,
                'emergency_contact_name': 'Moses Namutebi',
                'emergency_contact_relationship': 'parent',
                'emergency_contact_phone': '+256701234000', 'emergency_contact_email': '',
                'status': Application.APPROVED,
            },
            {
                'first_name': 'Samuel', 'last_name': 'Wasswa', 'other_names': 'James',
                'date_of_birth': '1998-11-30', 'gender': 'male', 'nationality': 'Ugandan',
                'national_id': 'CM91998300001S', 'phone_number': '+256709988776',
                'email': 'samuel.wasswa@gmail.com',
                'physical_address': 'Mukono Town', 'district': 'Mukono',
                'program_applied': mechanics,
                'highest_education_level': 'a_level',
                'last_school_attended': 'Mukono High School', 'year_of_completion': 2017,
                'emergency_contact_name': 'Ruth Wasswa',
                'emergency_contact_relationship': 'parent',
                'emergency_contact_phone': '+256756677889', 'emergency_contact_email': '',
                'status': Application.APPROVED,
            },
            {
                'first_name': 'Brian', 'last_name': 'Sekandi', 'other_names': '',
                'date_of_birth': '2005-03-18', 'gender': 'male', 'nationality': 'Ugandan',
                'national_id': '', 'phone_number': '+256780001122',
                'email': 'brian.sekandi@gmail.com',
                'physical_address': 'Entebbe Road, Wakiso', 'district': 'Wakiso',
                'program_applied': mechanics,
                'highest_education_level': 'primary',
                'last_school_attended': 'St. Peters Primary School', 'year_of_completion': 2020,
                'emergency_contact_name': 'Paul Sekandi',
                'emergency_contact_relationship': 'parent',
                'emergency_contact_phone': '+256712233445', 'emergency_contact_email': '',
                'status': Application.REJECTED,
                'rejection_reason': (
                    'Applicant does not meet the minimum entry requirement for Diploma level. '
                    'Please apply for a Junior Certificate or National Certificate program.'
                ),
            },
        ]

        admin_user = (
            User.objects.filter(role=User.SUPER_ADMIN).first()
            or User.objects.filter(is_superuser=True).first()
        )

        enrollments = []
        for data in app_data:
            status = data.pop('status')
            rejection_reason = data.pop('rejection_reason', '')

            app, created = Application.objects.get_or_create(
                email=data['email'],
                defaults=data,
            )

            if not created:
                self.stdout.write(f'  [Exists ] {app.full_name} ({status})')
                existing = Enrollment.objects.filter(application=app).first()
                if existing:
                    enrollments.append(existing)
                continue

            app.status = status
            app.rejection_reason = rejection_reason
            if status in [Application.APPROVED, Application.REJECTED, Application.UNDER_REVIEW]:
                app.reviewed_by = admin_user
                app.reviewed_at = timezone.now()
            app.save()

            if status == Application.APPROVED:
                enrollment = self._create_enrolled_student(app)
                if enrollment:
                    enrollments.append(enrollment)

            self.stdout.write(f'  [Created] {app.full_name} ({status})')

        return enrollments

    def _create_enrolled_student(self, application):
        if User.objects.filter(email=application.email).exists():
            return Enrollment.objects.filter(
                student__email=application.email
            ).first()

        user = User.objects.create_user(
            username=application.email,
            email=application.email,
            first_name=application.first_name,
            last_name=application.last_name,
            phone=application.phone_number,
            role=User.STUDENT,
            password='Student@2024!',
            is_verified=True,
        )
        enrollment = Enrollment.objects.create(
            student=user,
            application=application,
            program=application.program_applied,
        )
        StudentProfile.objects.create(user=user)
        application.applicant_user = user
        application.save(update_fields=['applicant_user'])

        Notification.objects.create(
            recipient=user,
            title='Welcome to MLS Foundation Portal!',
            message=(
                f'Dear {user.first_name}, your application has been approved and your account is now active. '
                f'Your Student ID is {enrollment.student_number}. Welcome aboard!'
            ),
        )
        return enrollment

    # ------------------------------------------------------------------
    # Timetable
    # ------------------------------------------------------------------

    def _seed_timetable(self, programs):
        tailoring = programs.get('Tailoring & Fashion Design')
        elec = programs.get('Electrical Installation')

        if not tailoring or not elec:
            return

        entries = [
            # Tailoring — Year 1, Term 1
            dict(program=tailoring, year=1, term='term_1', academic_year='2025/2026',
                 day=1, start_time=datetime.time(8, 0), end_time=datetime.time(10, 0),
                 subject='Introduction to Tailoring', venue='Sewing Room A'),
            dict(program=tailoring, year=1, term='term_1', academic_year='2025/2026',
                 day=1, start_time=datetime.time(10, 30), end_time=datetime.time(12, 30),
                 subject='Basic Sewing Techniques', venue='Sewing Room A'),
            dict(program=tailoring, year=1, term='term_1', academic_year='2025/2026',
                 day=2, start_time=datetime.time(8, 0), end_time=datetime.time(10, 0),
                 subject='Fabric Knowledge & Selection', venue='Classroom 2'),
            dict(program=tailoring, year=1, term='term_1', academic_year='2025/2026',
                 day=3, start_time=datetime.time(8, 0), end_time=datetime.time(11, 0),
                 subject='Measurements & Cutting', venue='Sewing Room B'),
            dict(program=tailoring, year=1, term='term_1', academic_year='2025/2026',
                 day=4, start_time=datetime.time(9, 0), end_time=datetime.time(11, 0),
                 subject='Pattern Making', venue='Sewing Room A'),
            dict(program=tailoring, year=1, term='term_1', academic_year='2025/2026',
                 day=5, start_time=datetime.time(8, 0), end_time=datetime.time(10, 0),
                 subject='Garment Construction', venue='Sewing Room B'),
            # Electrical — Year 1, Term 1
            dict(program=elec, year=1, term='term_1', academic_year='2025/2026',
                 day=1, start_time=datetime.time(8, 0), end_time=datetime.time(10, 0),
                 subject='Basic Electrical Theory', venue='Lab 1'),
            dict(program=elec, year=1, term='term_1', academic_year='2025/2026',
                 day=2, start_time=datetime.time(8, 0), end_time=datetime.time(11, 0),
                 subject='DC Circuits & Components', venue='Lab 1'),
            dict(program=elec, year=1, term='term_1', academic_year='2025/2026',
                 day=3, start_time=datetime.time(10, 0), end_time=datetime.time(12, 0),
                 subject='Electrical Safety & Regulations', venue='Classroom 1'),
            dict(program=elec, year=1, term='term_1', academic_year='2025/2026',
                 day=4, start_time=datetime.time(8, 0), end_time=datetime.time(10, 0),
                 subject='Tools, Equipment & Materials', venue='Workshop'),
            dict(program=elec, year=1, term='term_1', academic_year='2025/2026',
                 day=5, start_time=datetime.time(8, 0), end_time=datetime.time(11, 0),
                 subject='Practical: Wiring Exercise', venue='Lab 1'),
        ]

        count = 0
        for e in entries:
            _, created = TimetableEntry.objects.get_or_create(
                program=e['program'],
                year=e['year'],
                term=e['term'],
                academic_year=e['academic_year'],
                day=e['day'],
                start_time=e['start_time'],
                defaults=e,
            )
            if created:
                count += 1
        self.stdout.write(f'  Created {count} timetable entries')

    # ------------------------------------------------------------------
    # Payments
    # ------------------------------------------------------------------

    def _seed_payments(self, enrollments):
        if not enrollments:
            self.stdout.write('  No enrollments found — skipping payments')
            return

        admin_user = (
            User.objects.filter(role=User.SUPER_ADMIN).first()
            or User.objects.filter(is_superuser=True).first()
        )

        count = 0
        for enrollment in enrollments:
            fee = enrollment.program.tuition_fee
            payments = [
                dict(payment_type=Payment.TUITION, term='term_1', academic_year='2025/2026',
                     amount=fee, payment_method='mobile_money',
                     reference=f'MM-{enrollment.student_number}-T1',
                     payment_date=datetime.date(2025, 1, 10),
                     notes='Term 1 tuition fee'),
                dict(payment_type=Payment.TUITION, term='term_2', academic_year='2025/2026',
                     amount=fee, payment_method='bank_transfer',
                     reference=f'BK-{enrollment.student_number}-T2',
                     payment_date=datetime.date(2025, 4, 5),
                     notes='Term 2 tuition fee'),
                dict(payment_type=Payment.PRACTICAL, term='term_1', academic_year='2025/2026',
                     amount=enrollment.program.practical_fee, payment_method='cash',
                     reference='', payment_date=datetime.date(2025, 1, 12),
                     notes='Practical fee'),
                dict(payment_type=Payment.ASSESSMENT, term='term_1', academic_year='2025/2026',
                     amount=enrollment.program.assessment_fee, payment_method='mobile_money',
                     reference=f'MM-{enrollment.student_number}-ASS',
                     payment_date=datetime.date(2025, 2, 20),
                     notes='Assessment / exam fee'),
            ]
            for p in payments:
                _, created = Payment.objects.get_or_create(
                    enrollment=enrollment,
                    payment_type=p['payment_type'],
                    term=p['term'],
                    academic_year=p['academic_year'],
                    defaults={**p, 'enrollment': enrollment, 'recorded_by': admin_user},
                )
                if created:
                    count += 1

        self.stdout.write(f'  Created {count} payment records')

    # ------------------------------------------------------------------
    # Certificates
    # ------------------------------------------------------------------

    def _seed_certificates(self, enrollments):
        if not enrollments:
            return

        admin_user = (
            User.objects.filter(role=User.SUPER_ADMIN).first()
            or User.objects.filter(is_superuser=True).first()
        )

        enrollment = enrollments[0]
        _, created = Certificate.objects.get_or_create(
            enrollment=enrollment,
            defaults={
                'certificate_number': f'MLS-CERT-2025-{enrollment.student_number}',
                'issue_date': datetime.date(2025, 12, 15),
                'academic_year': '2025/2026',
                'notes': 'Successfully completed Year 1 of program.',
                'recorded_by': admin_user,
            },
        )
        if created:
            self.stdout.write(f'  [Created] Certificate for {enrollment.student.get_full_name()}')
        else:
            self.stdout.write(f'  [Exists ] Certificate for {enrollment.student.get_full_name()}')

    # ------------------------------------------------------------------
    # Testimonials
    # ------------------------------------------------------------------

    def _seed_testimonials(self, programs):
        tailoring = programs.get('Tailoring & Fashion Design')
        elec = programs.get('Electrical Installation')
        mechanics = programs.get('Motor Vehicle Mechanics')

        data = [
            {
                'name': 'Christine Namuli',
                'role': 'Graduate — Tailoring & Fashion Design',
                'program': tailoring,
                'quote': (
                    'Before joining MLS Foundation, I had no skills and no income. '
                    'Today I run my own tailoring business from home and employ two people. '
                    'This foundation truly changed my life.'
                ),
                'is_published': True,
                'display_order': 1,
            },
            {
                'name': 'David Ouma',
                'role': 'Graduate — Electrical Installation',
                'program': elec,
                'quote': (
                    'The hands-on training at MLS Foundation gave me the practical skills '
                    'employers are looking for. Within two months of graduating, I had a full-time job. '
                    'I am grateful for this opportunity.'
                ),
                'is_published': True,
                'display_order': 2,
            },
            {
                'name': 'Robert Kato',
                'role': 'Graduate — Motor Vehicle Mechanics',
                'program': mechanics,
                'quote': (
                    'The instructors are experienced and passionate. The workshop equipment '
                    'is modern and we got real industry exposure. I now own a small garage '
                    'and am proud of what I have built.'
                ),
                'is_published': True,
                'display_order': 3,
            },
        ]

        count = 0
        for item in data:
            _, created = Testimonial.objects.get_or_create(
                name=item['name'],
                defaults=item,
            )
            if created:
                count += 1
        self.stdout.write(f'  Created {count} testimonial(s)')

    # ------------------------------------------------------------------
    # Course content & quizzes
    # ------------------------------------------------------------------

    def _seed_content(self):
        admin = User.objects.filter(role=User.SUPER_ADMIN).first()

        # Pick one course per program for demo materials + quiz
        seed_courses = {
            'Motor Vehicle Mechanics':     ('Auto-Electrical Basics', 'MV-104'),
            'Electrical Installation':     ('Electrical Wiring & Safety', 'EI-101'),
            'Tailoring & Fashion Design':  ('Basic Sewing Techniques', 'TF-101'),
        }

        mat_count = 0
        quiz_count = 0

        for prog_name, (course_name, code) in seed_courses.items():
            course = Course.objects.filter(
                program__name=prog_name, name__icontains=course_name
            ).first()
            if not course:
                course = Course.objects.filter(program__name=prog_name).first()
            if not course:
                continue

            # --- Materials ---
            materials = [
                {
                    'title': 'Introduction Video',
                    'material_type': CourseMaterial.YOUTUBE,
                    'youtube_url': 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
                    'description': 'Watch this overview video before the first session.',
                    'order': 1,
                    'is_published': True,
                },
                {
                    'title': 'Course Notes — Week 1',
                    'material_type': CourseMaterial.NOTE,
                    'text_content': (
                        'Welcome to ' + course.name + '.\n\n'
                        'Learning Outcomes:\n'
                        '1. Understand the fundamental principles of this subject.\n'
                        '2. Apply practical techniques in the workshop.\n'
                        '3. Demonstrate safe working practices at all times.\n\n'
                        'Required Materials:\n'
                        '- Practical workbook\n'
                        '- Personal Protective Equipment (PPE)\n'
                        '- Tools as specified in the program handbook'
                    ),
                    'description': 'Week 1 notes — fundamentals and safety.',
                    'order': 2,
                    'is_published': True,
                },
                {
                    'title': 'Industry Reference Guide',
                    'material_type': CourseMaterial.LINK,
                    'external_url': 'https://www.uvtab.go.ug',
                    'description': 'Official UVTAB resource for this discipline.',
                    'order': 3,
                    'is_published': True,
                },
                {
                    'title': 'Supplementary Reading (Draft)',
                    'material_type': CourseMaterial.NOTE,
                    'text_content': 'This supplementary reading is still being prepared by your instructor.',
                    'order': 4,
                    'is_published': False,
                },
            ]

            for m_data in materials:
                _, created = CourseMaterial.objects.get_or_create(
                    course=course,
                    title=m_data['title'],
                    defaults={**m_data, 'uploaded_by': admin},
                )
                if created:
                    mat_count += 1

            # --- Quiz ---
            if Quiz.objects.filter(course=course).exists():
                continue

            quiz = Quiz.objects.create(
                course=course,
                title=course.name + ' — End of Unit Quiz',
                description='Test your understanding of ' + course.name + '. You need ' +
                            str(60) + '% to pass. Read your notes before attempting.',
                is_enabled=True,
                max_attempts=3,
                pass_score=60,
                created_by=admin,
            )
            quiz_count += 1

            questions = [
                {
                    'text': 'What is the primary purpose of Personal Protective Equipment (PPE) in the workshop?',
                    'choices': [
                        ('To make the work environment look professional', False),
                        ('To protect workers from injury and health hazards', True),
                        ('To comply with school uniform requirements', False),
                        ('To improve tool performance', False),
                    ],
                },
                {
                    'text': 'Which of the following best describes a safe working practice?',
                    'choices': [
                        ('Working quickly to finish tasks early', False),
                        ('Ignoring minor equipment faults to save time', False),
                        ('Inspecting tools before use and reporting defects', True),
                        ('Sharing PPE between multiple students', False),
                    ],
                },
                {
                    'text': 'What should you do immediately if you notice a safety hazard?',
                    'choices': [
                        ('Continue working and report it at the end of the day', False),
                        ('Ignore it if it does not affect your task', False),
                        ('Stop work and report it to the instructor immediately', True),
                        ('Ask a fellow student to handle it', False),
                    ],
                },
                {
                    'text': 'Which of these is NOT a recognised benefit of vocational training?',
                    'choices': [
                        ('Gaining practical, job-ready skills', False),
                        ('Improving employment prospects', False),
                        ('Guaranteed employment in a government role', True),
                        ('Building confidence through hands-on experience', False),
                    ],
                },
                {
                    'text': 'UVTAB stands for:',
                    'choices': [
                        ('Uganda Vocational Training and Apprenticeship Bureau', True),
                        ('Uganda Vocational Teachers Association Board', False),
                        ('Universal Vocational Training and Assessment Body', False),
                        ('Uganda Vocational Technical Accreditation Bureau', False),
                    ],
                },
            ]

            for i, q_data in enumerate(questions, 1):
                question = QuizQuestion.objects.create(
                    quiz=quiz,
                    question_text=q_data['text'],
                    order=i,
                )
                for choice_text, is_correct in q_data['choices']:
                    QuizChoice.objects.create(
                        question=question,
                        choice_text=choice_text,
                        is_correct=is_correct,
                    )

        self.stdout.write(
            '  Created ' + str(mat_count) + ' material(s), ' +
            str(quiz_count) + ' quiz(zes) with questions'
        )

    # ------------------------------------------------------------------
    # Clear
    # ------------------------------------------------------------------

    def _clear(self):
        self.stdout.write(self.style.WARNING('Clearing seed data...'))
        seed_emails = [
            'derrick.mugisha@gmail.com', 'aisha.namukasa@yahoo.com',
            'ronald.kiggundu@gmail.com', 'patricia.namutebi@gmail.com',
            'samuel.wasswa@gmail.com', 'brian.sekandi@gmail.com',
        ]
        seed_usernames = ['teacher.ssemakula', 'teacher.nakato']
        Application.objects.filter(email__in=seed_emails).delete()
        User.objects.filter(username__in=seed_usernames + seed_emails).delete()
        Testimonial.objects.filter(name__in=['Christine Namuli', 'David Ouma', 'Robert Kato']).delete()
        Course.objects.all().delete()
        TimetableEntry.objects.all().delete()
        Program.objects.all().delete()
        self.stdout.write('  Cleared.')
