"""
Seed a demo certification program with 100 MCQ questions.
Usage: python manage.py seed_certifications
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone

from apps.certifications.models import (
    CertificationProgram,
    ExamChoice,
    ExamQuestion,
    TestScheduleSlot,
    TestingCenter,
)


SAMPLE_TOPICS = [
    ('Python basics', [
        ('What is the output of print(2 ** 3)?', ['5', '6', '8', '9'], 'c'),
        ('Which keyword defines a function in Python?', ['func', 'def', 'function', 'define'], 'b'),
        ('What data type is True?', ['string', 'integer', 'boolean', 'float'], 'c'),
        ('Which symbol starts a comment?', ['//', '#', '/*', '--'], 'b'),
        ('What does len([1,2,3]) return?', ['2', '3', '4', 'Error'], 'b'),
    ]),
    ('Web & Django', [
        ('Django is mainly a:', ['Database', 'Web framework', 'OS', 'Browser'], 'b'),
        ('Which file usually contains URL routes?', ['models.py', 'urls.py', 'admin.py', 'apps.py'], 'b'),
        ('HTTP status 404 means:', ['OK', 'Created', 'Not Found', 'Server Error'], 'c'),
        ('CSS is used for:', ['Styling', 'Database', 'Authentication', 'Email'], 'a'),
        ('Which tag creates a hyperlink in HTML?', ['<img>', '<a>', '<link>', '<p>'], 'b'),
    ]),
    ('Databases', [
        ('SQL stands for:', ['Structured Query Language', 'Simple Quick List', 'Server Query Logic', 'None'], 'a'),
        ('Primary key must be:', ['Nullable', 'Unique', 'Duplicate', 'Optional always'], 'b'),
        ('Which command retrieves rows?', ['INSERT', 'UPDATE', 'SELECT', 'DELETE'], 'c'),
        ('MySQL default port is often:', ['80', '443', '3306', '8080'], 'c'),
        ('A foreign key references:', ['Another table key', 'CSS class', 'HTML id', 'Python module'], 'a'),
    ]),
    ('Security & networking', [
        ('HTTPS encrypts:', ['Traffic in transit', 'Only images', 'CPU heat', 'Disk format'], 'a'),
        ('A strong password should be:', ['Short', 'Reused everywhere', 'Long and unique', 'Only digits'], 'c'),
        ('Phishing is typically:', ['Hardware failure', 'Social engineering attack', 'DB backup', 'CSS bug'], 'b'),
        ('Firewall mainly:', ['Filters network traffic', 'Writes Python', 'Designs UI', 'Prints certificates'], 'a'),
        ('2FA adds:', ['Second authentication factor', 'Two databases', 'Two domains', 'Two CPUs'], 'a'),
    ]),
]


def _expand_to_n(n=800):
    """Build n question tuples by cycling sample banks with numbered variants."""
    base = []
    for topic, items in SAMPLE_TOPICS:
        for text, choices, correct in items:
            base.append((topic, text, choices, correct))

    questions = []
    i = 0
    while len(questions) < n:
        topic, text, choices, correct = base[i % len(base)]
        num = len(questions) + 1
        qtext = f'[{topic} #{num}] {text}'
        questions.append((qtext, choices, correct, num))
        i += 1
    return questions


class Command(BaseCommand):
    help = 'Create a demo certification program with 800+ MCQs (100 drawn randomly per exam)'

    @transaction.atomic
    def handle(self, *args, **options):
        program, created = CertificationProgram.objects.get_or_create(
            slug='python-skill-certification',
            defaults={
                'title': 'Python Skill Certification',
                'short_description': 'Prove your Python & web fundamentals with a random 100-MCQ exam from an 800+ question bank.',
                'full_description': (
                    'This certification is for candidates who already have practical skills '
                    'and need an official, verifiable certificate.\n\n'
                    'Pay the fee, schedule at a TSN Digital Center or remote, join a live unlock, '
                    'then take a random 100-question MCQ exam drawn from a bank of at least 800 questions '
                    '(70% to pass).'
                ),
                'fee': 4999,
                'reattempt_fee': None,
                'questions_per_exam': 100,
                'min_question_bank': 800,
                'passing_score': 70,
                'time_limit_minutes': 120,
                'max_attempts': 3,
                'require_proctor': True,
                'allow_center_exam': True,
                'allow_remote_exam': True,
                'meeting_instructions': (
                    'Join the scheduled Zoom/Meet session with your assigned teacher or consultant.\n'
                    'Keep your camera on for the full exam.\n'
                    'Your proctor will give you a one-time unlock code (EXAM-XXXX) to start the test.'
                ),
                'is_published': True,
            },
        )
        if not created:
            self.stdout.write('Program already exists — refreshing question bank to 800 MCQs...')
            program.questions.all().delete()
            program.passing_score = 70
            program.max_attempts = 3
            program.require_proctor = True
            program.allow_center_exam = True
            program.allow_remote_exam = True
            program.questions_per_exam = 100
            program.min_question_bank = 800
            if not program.meeting_instructions:
                program.meeting_instructions = (
                    'Join the scheduled Zoom/Meet session with your assigned teacher or consultant.\n'
                    'Keep your camera on for the full exam.\n'
                    'Your proctor will give you a one-time unlock code (EXAM-XXXX) to start the test.'
                )
            program.save()

        question_rows = []
        choice_rows = []
        for text, choices, correct, order in _expand_to_n(800):
            q = ExamQuestion(
                program=program,
                text=text,
                order=order,
                is_active=True,
            )
            question_rows.append(q)

        ExamQuestion.objects.bulk_create(question_rows, batch_size=200)
        # Reload with IDs
        created_qs = list(ExamQuestion.objects.filter(program=program).order_by('order', 'id'))
        labels = ['a', 'b', 'c', 'd']
        for q, (text, choices, correct, order) in zip(created_qs, _expand_to_n(800)):
            for idx, choice_text in enumerate(choices):
                choice_rows.append(ExamChoice(
                    question=q,
                    text=choice_text,
                    is_correct=(labels[idx] == correct),
                ))
        ExamChoice.objects.bulk_create(choice_rows, batch_size=500)

        center, _ = TestingCenter.objects.get_or_create(
            slug='tsn-digital-center',
            defaults={
                'name': 'TSN Digital Center',
                'address': 'Main Campus\nNear City Plaza\nOpen Sat–Thu, 9:00 AM – 6:00 PM',
                'city': 'Karachi',
                'phone': '+92-300-0000000',
                'email': 'center@tsndigital.academy',
                'directions': (
                    'Bring a valid photo ID.\n'
                    'Arrive 15 minutes before your booked slot.\n'
                    'Staff will verify your booking and issue an unlock code.'
                ),
                'is_active': True,
                'sort_order': 1,
            },
        )
        today = timezone.localdate()
        from datetime import time, timedelta
        created_slots = 0
        for day_offset in (1, 3, 7, 14):
            d = today + timedelta(days=day_offset)
            for start_h, end_h in ((10, 12), (14, 16)):
                _, made = TestScheduleSlot.objects.get_or_create(
                    center=center,
                    date=d,
                    start_time=time(start_h, 0),
                    end_time=time(end_h, 0),
                    defaults={
                        'program': None,
                        'capacity': 20,
                        'is_active': True,
                        'notes': 'Certification exam window',
                    },
                )
                if made:
                    created_slots += 1

        self.stdout.write(self.style.SUCCESS(
            f'Certification ready: "{program.title}" with {program.active_question_count} MCQs. '
            f'Slug: {program.slug}. Center: {center.name} (+{created_slots} new slots).'
        ))
