"""
Seed Part 1 categories + exam tracks (courses).

Usage (after migrate):
  python manage.py seed_course_taxonomy
  python manage.py seed_course_taxonomy --reset   # deactivate prior seeded tracks, re-seed
"""
from decimal import Decimal

from django.core.management.base import BaseCommand
from django.utils.text import slugify

from apps.courses.models import (
    CATEGORY_BOTH,
    LEVEL_ADVANCED,
    LEVEL_BEGINNER,
    LEVEL_INTERMEDIATE,
    MODULE_TYPE_PROJECT,
    MODULE_TYPE_THEORY,
    PROJECT_SUBMIT_FIGMA,
    PROJECT_SUBMIT_GITHUB,
    PROJECT_SUBMIT_LIVE,
    Category,
    CertificateTemplate,
    Course,
    Module,
    Project,
)
from utils.choices import COURSE_PUBLISHED


# Seeded course slug prefix so --reset can find them
SEED_TAG = 'taxonomy-v1'

TAXONOMY = [
    {
        'name': 'Web Development',
        'slug': 'web-development',
        'description': 'Frontend, backend frameworks, CMS, and full-stack tracks.',
        'order': 1,
        'tracks': [
            {
                'title': 'Frontend Development (HTML/CSS/JavaScript)',
                'level': LEVEL_BEGINNER,
                'exam_fee': '4999',
                'learning_price': '14999',
                'requires_practical': False,
                'short': 'Build modern web UIs with HTML, CSS, and JavaScript.',
            },
            {
                'title': 'Web Development Fundamentals — Theory Track',
                'level': LEVEL_BEGINNER,
                'exam_fee': '3999',
                'learning_price': '9999',
                'requires_practical': False,
                'short': 'Theory-based web fundamentals — not a “certified developer” credential.',
                'description_extra': (
                    'Honestly labelled as a theory-based track. Assesses conceptual understanding '
                    'of how the web works; it is not a hands-on developer certification.'
                ),
            },
            {
                'title': 'Laravel Developer',
                'level': LEVEL_INTERMEDIATE,
                'exam_fee': '7999',
                'learning_price': '24999',
                'requires_practical': True,
                'short': 'Build production PHP apps with the Laravel framework.',
            },
            {
                'title': 'CodeIgniter Developer',
                'level': LEVEL_INTERMEDIATE,
                'exam_fee': '6999',
                'learning_price': '19999',
                'requires_practical': True,
                'short': 'PHP MVC development with CodeIgniter.',
            },
            {
                'title': 'ASP.NET MVC Developer',
                'level': LEVEL_INTERMEDIATE,
                'exam_fee': '7999',
                'learning_price': '24999',
                'requires_practical': True,
                'short': 'Enterprise web apps with ASP.NET MVC.',
            },
            {
                'title': 'WordPress Developer',
                'level': LEVEL_INTERMEDIATE,
                'exam_fee': '5999',
                'learning_price': '17999',
                'requires_practical': False,
                'short': 'Themes, plugins, and WordPress site builds.',
            },
            {
                'title': 'Full Stack Development (MERN/MEAN overview)',
                'level': LEVEL_ADVANCED,
                'exam_fee': '9999',
                'learning_price': '34999',
                'requires_practical': True,
                'short': 'Overview of MERN/MEAN full-stack architecture and delivery.',
            },
        ],
    },
    {
        'name': 'Programming Languages',
        'slug': 'programming-languages',
        'description': 'Core language tracks from beginner to advanced.',
        'order': 2,
        'tracks': [
            {'title': 'Python Programming (Beginner)', 'level': LEVEL_BEGINNER, 'exam_fee': '4999', 'learning_price': '14999', 'requires_practical': False, 'short': 'Python syntax, basics, and first programs.'},
            {'title': 'Python Programming (Advanced/Data Structures)', 'level': LEVEL_ADVANCED, 'exam_fee': '7999', 'learning_price': '24999', 'requires_practical': False, 'short': 'Data structures, algorithms concepts, and advanced Python.'},
            {'title': 'Java Programming Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '4999', 'learning_price': '14999', 'requires_practical': False, 'short': 'OOP and Java language fundamentals.'},
            {'title': 'C# Programming Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '4999', 'learning_price': '14999', 'requires_practical': False, 'short': 'C# language and .NET fundamentals.'},
            {'title': 'PHP Programming', 'level': LEVEL_BEGINNER, 'exam_fee': '4999', 'learning_price': '14999', 'requires_practical': False, 'short': 'Server-side PHP for the web.'},
        ],
    },
    {
        'name': 'Software Development & Engineering',
        'slug': 'software-development-engineering',
        'description': 'Process, data, APIs, version control, and QA fundamentals.',
        'order': 3,
        'tracks': [
            {'title': 'Software Development Life Cycle (SDLC) & Agile', 'level': LEVEL_BEGINNER, 'exam_fee': '4499', 'learning_price': '12999', 'requires_practical': False, 'short': 'SDLC phases and Agile ways of working.'},
            {'title': 'Database Management (SQL/MySQL)', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Relational databases and SQL with MySQL.'},
            {'title': 'API Development & REST Fundamentals', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'REST APIs, resources, and integration basics.'},
            {'title': 'Git & Version Control', 'level': LEVEL_BEGINNER, 'exam_fee': '3499', 'learning_price': '9999', 'requires_practical': False, 'short': 'Git workflows for teams and solo work.'},
            {'title': 'Software QA & Testing Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '4499', 'learning_price': '12999', 'requires_practical': False, 'short': 'Testing types, cases, and QA process basics.'},
        ],
    },
    {
        'name': 'Design',
        'slug': 'design',
        'description': 'Graphic, UI/UX, and tool-focused design certifications.',
        'order': 4,
        'tracks': [
            {
                'title': 'Graphic Design Fundamentals (theory + tool knowledge: Adobe Illustrator/Photoshop/Figma)',
                'level': LEVEL_BEGINNER,
                'exam_fee': '5999',
                'learning_price': '17999',
                'requires_practical': True,
                'short': 'Design theory plus Illustrator, Photoshop, and Figma tool knowledge.',
            },
            {'title': 'UI/UX Design Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '5999', 'learning_price': '17999', 'requires_practical': True, 'short': 'User research, wireframes, and interface design basics.'},
            {'title': 'Adobe Photoshop Certification', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Photoshop skills for digital imaging.'},
            {'title': 'Adobe Illustrator Certification', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Vector graphics with Adobe Illustrator.'},
            {'title': 'Figma for Product Design', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Product UI design and prototyping in Figma.'},
        ],
    },
    {
        'name': 'Digital Marketing',
        'slug': 'digital-marketing',
        'description': 'SEO, ads, content, email, and e-commerce marketing tracks.',
        'order': 5,
        'tracks': [
            {'title': 'Digital Marketing Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '4999', 'learning_price': '14999', 'requires_practical': False, 'short': 'Channels, funnels, and digital marketing basics.'},
            {
                'title': 'SEO Expert',
                'level': LEVEL_ADVANCED,
                'exam_fee': '9999',
                'learning_price': '29999',
                'requires_practical': False,
                'short': 'Flagship SEO track — tied to Lumosor methodology and practice.',
                'description_extra': 'Flagship certification track. Content and exam aligned with Lumosor SEO practice for the Pakistani and international markets.',
                'is_flagship': True,
            },
            {'title': 'Social Media Marketing (Meta/Instagram/TikTok Ads)', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5999', 'learning_price': '17999', 'requires_practical': False, 'short': 'Organic + paid social on Meta, Instagram, and TikTok.'},
            {'title': 'Google Ads / SEM Fundamentals', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5999', 'learning_price': '17999', 'requires_practical': False, 'short': 'Search ads, Quality Score, and SEM campaigns.'},
            {'title': 'Content Marketing & Copywriting', 'level': LEVEL_BEGINNER, 'exam_fee': '4499', 'learning_price': '12999', 'requires_practical': False, 'short': 'Content strategy and persuasive copy.'},
            {'title': 'Email Marketing Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '3999', 'learning_price': '11999', 'requires_practical': False, 'short': 'Lists, campaigns, and email automation basics.'},
            {'title': 'E-commerce Marketing (Shopify/Amazon/Daraz)', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5999', 'learning_price': '17999', 'requires_practical': False, 'short': 'Marketplace and store marketing for Shopify, Amazon, and Daraz.'},
        ],
    },
    {
        'name': 'AI & Emerging Tech',
        'slug': 'ai-emerging-tech',
        'description': 'AI literacy, generative tools, and no-code AI building.',
        'order': 6,
        'tracks': [
            {'title': 'AI Fundamentals & Prompt Engineering', 'level': LEVEL_BEGINNER, 'exam_fee': '4999', 'learning_price': '14999', 'requires_practical': False, 'short': 'How AI works and how to prompt effectively.'},
            {'title': 'Generative AI Tools (ChatGPT/Claude/Midjourney usage)', 'level': LEVEL_BEGINNER, 'exam_fee': '4499', 'learning_price': '12999', 'requires_practical': False, 'short': 'Practical use of leading generative AI tools.'},
            {'title': 'AI for Digital Marketing', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Apply AI across SEO, ads, and content workflows.'},
            {'title': 'AI for Content Creation', 'level': LEVEL_BEGINNER, 'exam_fee': '4499', 'learning_price': '12999', 'requires_practical': False, 'short': 'Create text, image, and media assets with AI.'},
            {
                'title': 'Machine Learning Fundamentals (concepts only, no coding requirement)',
                'level': LEVEL_BEGINNER,
                'exam_fee': '4999',
                'learning_price': '14999',
                'requires_practical': False,
                'short': 'ML concepts only — no coding requirement.',
            },
            {'title': 'No-Code AI App Building (using tools like Zapier/Make/Bubble)', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Automations and apps with Zapier, Make, and Bubble.'},
        ],
    },
    {
        'name': 'Business & Office Skills',
        'slug': 'business-office-skills',
        'description': 'Office productivity, freelancing, communication, and PM basics.',
        'order': 7,
        'tracks': [
            {'title': 'MS Excel for Business', 'level': LEVEL_BEGINNER, 'exam_fee': '3999', 'learning_price': '11999', 'requires_practical': False, 'short': 'Spreadsheets, formulas, and business reporting in Excel.'},
            {'title': 'MS Office Suite Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '3499', 'learning_price': '9999', 'requires_practical': False, 'short': 'Word, Excel, PowerPoint essentials.'},
            {'title': 'Freelancing & Remote Work Fundamentals', 'level': LEVEL_BEGINNER, 'exam_fee': '3999', 'learning_price': '11999', 'requires_practical': False, 'short': 'Profiles, clients, and remote work habits.'},
            {'title': 'Business Communication & Email Etiquette', 'level': LEVEL_BEGINNER, 'exam_fee': '2999', 'learning_price': '8999', 'requires_practical': False, 'short': 'Professional writing and email standards.'},
            {
                'title': 'Project Management Fundamentals (PM basics, not PMP)',
                'level': LEVEL_BEGINNER,
                'exam_fee': '4499',
                'learning_price': '12999',
                'requires_practical': False,
                'short': 'PM basics for teams — not a PMP exam prep course.',
            },
        ],
    },
    {
        'name': 'Data',
        'slug': 'data',
        'description': 'Spreadsheet analysis, Power BI, and SQL for analysts.',
        'order': 8,
        'tracks': [
            {'title': 'Data Analysis Fundamentals (Excel/Sheets based)', 'level': LEVEL_BEGINNER, 'exam_fee': '4499', 'learning_price': '12999', 'requires_practical': False, 'short': 'Analyze data in Excel and Google Sheets.'},
            {'title': 'Power BI Fundamentals', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5999', 'learning_price': '17999', 'requires_practical': False, 'short': 'Dashboards and visuals with Power BI.'},
            {'title': 'SQL for Data Analysis', 'level': LEVEL_INTERMEDIATE, 'exam_fee': '5499', 'learning_price': '15999', 'requires_practical': False, 'short': 'Query and shape data with SQL for analysis.'},
        ],
    },
]


def _money(value):
    return Decimal(str(value))


def _part3_pricing(track):
    """
    Suggested PKR starting prices (Part 3). Editable later in admin.
    """
    practical = track.get('requires_practical', False)
    level = track.get('level', LEVEL_BEGINNER)
    flagship = track.get('is_flagship', False)

    if practical:
        learning = Decimal('7000')
        mentorship = Decimal('10000')
        exam = Decimal('20000')
        reattempt = Decimal('6000')
        sub_monthly = Decimal('6000')
        weeks = 12
        est_months = 4
    else:
        learning = Decimal('5000')
        mentorship = Decimal('7000')
        exam = Decimal('13000')
        reattempt = Decimal('5000')
        sub_monthly = Decimal('3500')
        weeks = 8
        est_months = 3

    if level == LEVEL_ADVANCED and not practical:
        learning = Decimal('6500')
        exam = Decimal('15000')
        sub_monthly = Decimal('4500')
    if flagship:
        learning = Decimal('8000')
        mentorship = Decimal('12000')
        exam = Decimal('15000')
        sub_monthly = Decimal('5000')
        weeks = 10

    # Allow per-track overrides from TAXONOMY if present
    if track.get('learning_price'):
        learning = _money(track['learning_price'])
    if track.get('exam_fee'):
        exam = _money(track['exam_fee'])
    if track.get('mentorship_price'):
        mentorship = _money(track['mentorship_price'])
    if track.get('subscription_price_monthly'):
        sub_monthly = _money(track['subscription_price_monthly'])

    return {
        'learning_price': learning,
        'mentorship_price': mentorship,
        'exam_fee': exam,
        'direct_exam_only_price': exam,
        'reattempt_fee': reattempt,
        'bundle_discount_percent': 12,
        'currency': 'PKR',
        'duration_weeks': weeks,
        'subscription_enabled': True,
        'subscription_price_monthly': sub_monthly,
        'min_subscription_months': 1,
        'estimated_completion_months': est_months,
        'mentorship_available': True,
        'price': learning,
        'duration': f'{weeks} weeks (self-paced)',
    }


class Command(BaseCommand):
    help = 'Seed categories and exam-track courses for Part 1 taxonomy.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--reset',
            action='store_true',
            help='Deactivate previously seeded taxonomy courses, then re-seed.',
        )

    def handle(self, *args, **options):
        default_template, _ = CertificateTemplate.objects.get_or_create(
            slug='default-completion',
            defaults={
                'name': 'Default Certificate of Completion',
                'description': 'Standard academy certificate template (assets in later part).',
                'is_active': True,
            },
        )

        if options['reset']:
            deactivated = Course.objects.filter(slug__contains=f'-{SEED_TAG}').update(is_active=False, status='draft')
            self.stdout.write(self.style.WARNING(f'Deactivated {deactivated} previously seeded tracks.'))

        cat_count = 0
        course_count = 0
        module_count = 0

        for block in TAXONOMY:
            category, created = Category.objects.update_or_create(
                slug=block['slug'],
                defaults={
                    'name': block['name'],
                    'description': block['description'],
                    'applies_to': CATEGORY_BOTH,
                    'order': block['order'],
                    'is_active': True,
                },
            )
            if created:
                cat_count += 1

            for track in block['tracks']:
                base = slugify(track['title'])[:180] or 'track'
                slug = f'{base}-{SEED_TAG}'
                pricing = _part3_pricing(track)

                full_desc = track.get('description_extra') or (
                    f"{track['short']} Dual path: complete Learning Path modules then exam, "
                    f"or take the Direct Certification exam. Pass mark 70%, 100 MCQs."
                )
                if track.get('is_flagship'):
                    full_desc = f"[FLAGSHIP] {full_desc}"

                course, created = Course.objects.update_or_create(
                    slug=slug,
                    defaults={
                        'title': track['title'],
                        'category': category,
                        'short_description': track['short'][:300],
                        'full_description': full_desc,
                        'level': track['level'],
                        'pass_percentage': 70,
                        'question_count_per_attempt': 100,
                        'total_bank_size': 800,
                        'duration_minutes': 120,
                        'has_learning_content': True,
                        'requires_practical': track['requires_practical'],
                        'is_active': True,
                        'status': COURSE_PUBLISHED,
                        'certificate_template': default_template,
                        'learning_completion_required_percent': 100,
                        **pricing,
                    },
                )
                if created:
                    course_count += 1

                # ~20% theory / 80% practice: 1 theory + 4 project modules
                sample_modules = [
                    (0, MODULE_TYPE_THEORY, 'Introduction & Core Concepts', 'text', True,
                     f'Theory overview for {track["title"]}. Concepts, vocabulary, and how the certification works.'),
                    (1, MODULE_TYPE_PROJECT, 'Project Studio 1', 'mixed', False,
                     'Hands-on practice block linked to Project 1.'),
                    (2, MODULE_TYPE_PROJECT, 'Project Studio 2', 'mixed', False,
                     'Hands-on practice block linked to Project 2.'),
                    (3, MODULE_TYPE_PROJECT, 'Project Studio 3', 'mixed', False,
                     'Hands-on practice block linked to Project 3.'),
                    (4, MODULE_TYPE_PROJECT, 'Capstone Practice & Review', 'video', False,
                     'Final practice and exam prep checklist.'),
                ]
                for order, mtype, title, ctype, preview, body in sample_modules:
                    mod, mod_created = Module.objects.update_or_create(
                        course=course,
                        order=order,
                        defaults={
                            'title': title,
                            'description': body,
                            'module_type': mtype,
                            'content_type': ctype,
                            'content_body': body,
                            'content_url': '',
                            'is_free_preview': preview,
                        },
                    )
                    if mod_created:
                        module_count += 1

                # 3 real-world projects per track
                submit = PROJECT_SUBMIT_GITHUB
                if 'Design' in block['name'] or 'Figma' in track['title'] or 'Photoshop' in track['title'] or 'Illustrator' in track['title'] or 'UI/UX' in track['title']:
                    submit = PROJECT_SUBMIT_FIGMA
                if 'Marketing' in block['name'] or 'SEO' in track['title']:
                    submit = PROJECT_SUBMIT_LIVE

                project_specs = [
                    (0, f'{track["title"]} — Project 1: Foundations Build',
                     'Apply core skills on a small real-world brief. Submit via the required channel.'),
                    (1, f'{track["title"]} — Project 2: Client-Style Deliverable',
                     'Produce a portfolio-ready deliverable as if for a client or team.'),
                    (2, f'{track["title"]} — Project 3: Capstone Challenge',
                     'Integrate earlier skills into a longer capstone suitable for employers.'),
                ]
                for porder, ptitle, pdesc in project_specs:
                    Project.objects.update_or_create(
                        course=course,
                        order=porder,
                        defaults={
                            'title': ptitle,
                            'description': pdesc,
                            'submission_type': submit,
                            'rubric': {
                                'text': 'Completeness, quality, documentation, and alignment with brief.',
                                'criteria': {
                                    'completeness': 30,
                                    'quality': 40,
                                    'documentation': 20,
                                    'brief_alignment': 10,
                                },
                            },
                            'is_active': True,
                        },
                    )

        self.stdout.write(self.style.SUCCESS(
            f'Seed complete. Categories created: {cat_count}, '
            f'courses created: {course_count}, modules created: {module_count}. '
            f'(Existing matching slugs were updated.)'
        ))
        self.stdout.write('Run after migrate: python manage.py seed_course_taxonomy')
