"""
Management command to populate the database with demo seed data.

Usage:
    python manage.py seed_data
"""
from django.core.management.base import BaseCommand
from django.db import transaction

from apps.accounts.models import CustomUser
from apps.courses.models import Course, Module, Lesson
from apps.enrollments.models import Enrollment


TEACHER_EMAIL = 'teacher@demo.com'
STUDENT_EMAIL = 'student@demo.com'
DEFAULT_PASSWORD = 'Demo@12345'


class Command(BaseCommand):
    help = 'Seed the database with demo users and sample courses'

    def handle(self, *args, **options):
        self.stdout.write('Seeding demo data...')
        with transaction.atomic():
            teacher = self._create_teacher()
            student = self._create_student()
            courses = self._create_courses(teacher)
            self._create_enrollment(student, courses[0])

        self.stdout.write(self.style.SUCCESS(
            '\nSeed data created successfully!\n'
            f'  Teacher : {TEACHER_EMAIL}  /  {DEFAULT_PASSWORD}\n'
            f'  Student : {STUDENT_EMAIL}  /  {DEFAULT_PASSWORD}\n'
            '  (Set a superuser role to "admin" via Django admin or createsuperuser)\n'
        ))

    # ------------------------------------------------------------------ #
    # Private helpers                                                      #
    # ------------------------------------------------------------------ #

    def _create_teacher(self):
        if CustomUser.objects.filter(email=TEACHER_EMAIL).exists():
            self.stdout.write(f'  Teacher already exists ({TEACHER_EMAIL}), skipping.')
            return CustomUser.objects.get(email=TEACHER_EMAIL)

        teacher = CustomUser.objects.create_user(
            username='demo_teacher',
            email=TEACHER_EMAIL,
            password=DEFAULT_PASSWORD,
            full_name='Alice Johnson',
            role='teacher',
        )
        self.stdout.write(f'  Created teacher: {teacher.email}')
        return teacher

    def _create_student(self):
        if CustomUser.objects.filter(email=STUDENT_EMAIL).exists():
            self.stdout.write(f'  Student already exists ({STUDENT_EMAIL}), skipping.')
            return CustomUser.objects.get(email=STUDENT_EMAIL)

        student = CustomUser.objects.create_user(
            username='demo_student',
            email=STUDENT_EMAIL,
            password=DEFAULT_PASSWORD,
            full_name='Bob Smith',
            role='student',
        )
        self.stdout.write(f'  Created student: {student.email}')
        return student

    def _create_courses(self, teacher):
        courses_data = [
            {
                'title': 'Python for Beginners',
                'short_description': 'A comprehensive introduction to Python programming.',
                'full_description': (
                    'Learn variables, loops, functions, and object-oriented concepts '
                    'through practical, hands-on exercises. Perfect for absolute beginners.'
                ),
                'status': 'published',
                'price': '29.99',
                'duration': '10 hours',
                'modules': [
                    {
                        'title': 'Getting Started',
                        'lessons': [
                            {'title': 'Installing Python & VS Code', 'is_preview': True},
                            {'title': 'Your First Python Script', 'is_preview': True},
                        ],
                    },
                    {
                        'title': 'Core Concepts',
                        'lessons': [
                            {'title': 'Variables and Data Types', 'is_preview': False},
                            {'title': 'Control Flow: if / else', 'is_preview': False},
                            {'title': 'Loops: for and while', 'is_preview': False},
                        ],
                    },
                ],
            },
            {
                'title': 'Django Web Development',
                'short_description': 'Build real-world web applications with Django.',
                'full_description': (
                    'Covers models, views, templates, forms, authentication, and deployment. '
                    'You will build a production-ready project from scratch.'
                ),
                'status': 'published',
                'price': '49.99',
                'duration': '20 hours',
                'modules': [
                    {
                        'title': 'Django Basics',
                        'lessons': [
                            {'title': 'Project Setup and Structure', 'is_preview': True},
                            {'title': 'Models and Migrations', 'is_preview': False},
                        ],
                    },
                    {
                        'title': 'Views & Templates',
                        'lessons': [
                            {'title': 'Class-Based Views', 'is_preview': False},
                            {'title': 'Template Inheritance', 'is_preview': False},
                        ],
                    },
                ],
            },
            {
                'title': 'Bootstrap 5 UI Design',
                'short_description': 'Create beautiful, responsive interfaces using Bootstrap 5.',
                'full_description': (
                    'Grid system, components, utilities, and customization. '
                    'Learn to build professional UIs without writing custom CSS from scratch.'
                ),
                'status': 'draft',
                'price': '19.99',
                'duration': '6 hours',
                'modules': [
                    {
                        'title': 'Bootstrap Fundamentals',
                        'lessons': [
                            {'title': 'Introduction to Bootstrap 5', 'is_preview': True},
                            {'title': 'The Grid System', 'is_preview': False},
                        ],
                    },
                ],
            },
        ]

        created_courses = []
        for data in courses_data:
            course, created = Course.objects.get_or_create(
                title=data['title'],
                defaults={
                    'short_description': data['short_description'],
                    'full_description': data['full_description'],
                    'status': data['status'],
                    'price': data['price'],
                    'duration': data['duration'],
                },
            )
            if created:
                course.teachers.add(teacher)
                self._create_modules(course, data['modules'])
                self.stdout.write(f'  Created course: {course.title}')
            else:
                self.stdout.write(f'  Course already exists: {course.title}, skipping.')

            created_courses.append(course)

        return created_courses

    def _create_modules(self, course, modules_data):
        for order, mod_data in enumerate(modules_data, start=1):
            module = Module.objects.create(
                course=course,
                title=mod_data['title'],
                order=order,
            )
            for lesson_order, lesson_data in enumerate(mod_data['lessons'], start=1):
                Lesson.objects.create(
                    module=module,
                    title=lesson_data['title'],
                    content=f"Demo content for '{lesson_data['title']}'.",
                    order=lesson_order,
                    is_preview=lesson_data['is_preview'],
                )

    def _create_enrollment(self, student, course):
        enrollment, created = Enrollment.objects.get_or_create(
            student=student,
            course=course,
            defaults={'status': 'pending'},
        )
        if created:
            self.stdout.write(
                f'  Created pending enrollment: {student.email} → {course.title}'
            )
        else:
            self.stdout.write(
                f'  Enrollment already exists: {student.email} → {course.title}, skipping.'
            )
