from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from courses.models import Category, Instructor, Course, Enrollment, Headline, Video, CourseFile, Review

User = get_user_model()

class Command(BaseCommand):
    help = 'Seeds database with executive business coach masterclass content'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS("Starting database seeding..."))

        # 1. Create Categories
        cat_leadership, _ = Category.objects.get_or_create(
            slug="executive-leadership",
            defaults={'name': "Executive Leadership", 'icon': "bi-briefcase-fill", 'description': "C-Suite governance, team alignment, and high-performance scaling."}
        )
        cat_sales, _ = Category.objects.get_or_create(
            slug="sales-conversion",
            defaults={'name': "High-Ticket Sales", 'icon': "bi-graph-up-arrow", 'description': "Mastering negotiation, B2B deal structuring, and enterprise selling."}
        )
        cat_ai, _ = Category.objects.get_or_create(
            slug="ai-automation",
            defaults={'name': "AI & Systems", 'icon': "bi-cpu-fill", 'description': "Leveraging AI agents, automated funnels, and operational efficiency."}
        )
        cat_wealth, _ = Category.objects.get_or_create(
            slug="wealth-finance",
            defaults={'name': "Financial Strategy", 'icon': "bi-bank", 'description': "Cashflow engineering, valuation multipliers, and capital allocation."}
        )

        # 2. Create Instructor
        instructor, _ = Instructor.objects.get_or_create(
            name="Dr. Alexander Vance",
            defaults={
                'title': "Senior Executive Coach & Forbes 30u30 Mentor",
                'bio': "Former McKinsey partner turned serial tech investor. Has advised over 12,000 CEOs and scaled 4 companies to $100M+ exits.",
                'avatar_url': "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=400&q=80",
                'rating': 4.9,
                'students_count': 12500
            }
        )

        # 3. Create Demo Superuser / Test Executive User
        admin_user, _ = User.objects.get_or_create(
            phone="09123456789",
            defaults={'name': "Alexander Wright (CEO)", 'email': "ceo@businesscoach.com", 'is_staff': True, 'is_superuser': True}
        )
        admin_user.set_password("admin123")
        admin_user.save()

        # 4. Create Masterclasses
        courses_data = [
            {
                "name": "10x Revenue Executive Leadership Masterclass",
                "slug": "10x-revenue-executive-leadership",
                "course_id": "COURSE-EXEC-10X",
                "category": cat_leadership,
                "tagline": "Architect high-performing C-Suite teams and build predictable 8-figure revenue engines.",
                "description": "This signature executive program breaks down the exact operational blueprints used by Silicon Valley founders to scale from $1M to $50M ARR. Master executive decision frameworks, board presentation mastery, organizational alignment, and rapid customer acquisition systems.",
                "price": 999,
                "discount_price": 499,
                "is_featured": True,
                "badge_text": "BESTSELLER",
                "level": "Executive",
                "duration": "18.5 Hours",
                "rating": 4.95,
                "enrolled_count": 4820,
                "cover_url": "https://images.unsplash.com/photo-1551836022-d5d88e9218df?auto=format&fit=crop&w=1200&q=80",
                "demo_video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1",
                "headlines": [
                    {
                        "title": "Module 1: The CEO Operating System (CEO-OS)",
                        "videos": [
                            {"title": "Lesson 1.1: Time Auditing & Executive Focus", "duration": "22 min", "preview": True, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                            {"title": "Lesson 1.2: Structuring Your Executive Leadership Team", "duration": "35 min", "preview": False, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                            {"title": "Lesson 1.3: Weekly & Monthly KPIs Dashboard Setup", "duration": "28 min", "preview": False, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                        ]
                    },
                    {
                        "title": "Module 2: High-Margin Product Strategy",
                        "videos": [
                            {"title": "Lesson 2.1: Designing Offer Value Stack ($50k+ Retainers)", "duration": "40 min", "preview": False, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                            {"title": "Lesson 2.2: Pricing Psychology & Elasticity Testing", "duration": "31 min", "preview": False, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                        ]
                    }
                ],
                "files": [
                    {"title": "10x CEO Financial Dashboard (Excel)", "url": "https://example.com/downloads/ceo_financial_model.xlsx", "size": "4.2 MB"},
                    {"title": "Executive Hiring Blueprint PDF", "url": "https://example.com/downloads/hiring_blueprint.pdf", "size": "1.8 MB"}
                ]
            },
            {
                "name": "High-Ticket Enterprise Sales & Negotiation Mastery",
                "slug": "high-ticket-enterprise-sales",
                "course_id": "COURSE-SALES-HT",
                "category": cat_sales,
                "tagline": "Close $100k+ deals with corporate clients without discounting or endless sales cycles.",
                "description": "Learn the psychological techniques and negotiation frameworks required to close enterprise contracts. Covers cold executive outreach, discovery call mastery, handling procurement pushback, and structuring multi-year service contracts.",
                "price": 799,
                "discount_price": 349,
                "is_featured": True,
                "badge_text": "EXECUTIVE CHOICE",
                "level": "Mastery",
                "duration": "14.2 Hours",
                "rating": 4.92,
                "enrolled_count": 3150,
                "cover_url": "https://images.unsplash.com/photo-1556761175-5973dc0f32e7?auto=format&fit=crop&w=1200&q=80",
                "demo_video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1",
                "headlines": [
                    {
                        "title": "Module 1: Enterprise Discovery & Value Mapping",
                        "videos": [
                            {"title": "Lesson 1.1: The SPIN & MEDDPICC Sales Framework", "duration": "30 min", "preview": True, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                            {"title": "Lesson 1.2: Uncovering Latent Executive Pain Points", "duration": "25 min", "preview": False, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                        ]
                    }
                ],
                "files": [
                    {"title": "Enterprise Sales Proposal Template (.DOCX)", "url": "https://example.com/downloads/proposal_template.docx", "size": "2.1 MB"}
                ]
            },
            {
                "name": "AI Automation & Systems Engineering for CEOs",
                "slug": "ai-automation-systems-for-ceos",
                "course_id": "COURSE-AI-AUTO",
                "category": cat_ai,
                "tagline": "Replace 80% of repetitive operational tasks using AI autonomous agents & custom workflows.",
                "description": "Step-by-step masterclass on integrating LLMs, Zapier/Make automation, AI customer support reps, automated sales outreach, and intelligent data dashboards into your business operations.",
                "price": 649,
                "discount_price": 299,
                "is_featured": True,
                "badge_text": "HOT & TRENDING",
                "level": "Executive",
                "duration": "12.0 Hours",
                "rating": 4.88,
                "enrolled_count": 2890,
                "cover_url": "https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&w=1200&q=80",
                "demo_video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1",
                "headlines": [
                    {
                        "title": "Module 1: AI Agent Ecosystems for Operations",
                        "videos": [
                            {"title": "Lesson 1.1: Building Custom Knowledge Bases & GPTs", "duration": "28 min", "preview": True, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                            {"title": "Lesson 1.2: Automating Lead Enrichment & Outreach", "duration": "32 min", "preview": False, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                        ]
                    }
                ],
                "files": [
                    {"title": "Zapier & Make Automation Blueprints JSON", "url": "https://example.com/downloads/ai_blueprints.json", "size": "850 KB"}
                ]
            },
            {
                "name": "Corporate Finance, Capital Allocation & M&A Strategy",
                "slug": "corporate-finance-capital-allocation",
                "course_id": "COURSE-FIN-MA",
                "category": cat_wealth,
                "tagline": "Optimize cash flow, minimize tax liabilities, and position your company for a 10x exit valuation.",
                "description": "Master high-level financial engineering, debt vs equity financing, EBITDA expansion tactics, tax strategy for business owners, and preparation for strategic acquisition.",
                "price": 1200,
                "discount_price": 599,
                "is_featured": False,
                "badge_text": "VIP ONLY",
                "level": "Foundational",
                "duration": "16.8 Hours",
                "rating": 4.97,
                "enrolled_count": 1420,
                "cover_url": "https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=1200&q=80",
                "demo_video_url": "https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1",
                "headlines": [
                    {
                        "title": "Module 1: Valuation Multipliers & M&A Readiness",
                        "videos": [
                            {"title": "Lesson 1.1: Calculating EBITDA & Enterprise Value", "duration": "45 min", "preview": True, "url": "https://www.youtube.com/embed/dQw4w9WgXcQ"},
                        ]
                    }
                ],
                "files": [
                    {"title": "M&A Valuation Financial Sheet (XLSM)", "url": "https://example.com/downloads/valuation_sheet.xlsm", "size": "5.6 MB"}
                ]
            }
        ]

        for cdata in courses_data:
            headlines_data = cdata.pop("headlines")
            files_data = cdata.pop("files")
            
            course, _ = Course.objects.get_or_create(
                slug=cdata["slug"],
                defaults={**cdata, "instructor": instructor}
            )

            # Create Headlines & Videos
            for h_idx, hdata in enumerate(headlines_data):
                videos_data = hdata.pop("videos")
                headline, _ = Headline.objects.get_or_create(
                    course=course,
                    title=hdata["title"],
                    defaults={"order": h_idx}
                )
                for v_idx, vdata in enumerate(videos_data):
                    Video.objects.get_or_create(
                        course=course,
                        headline=headline,
                        title=vdata["title"],
                        defaults={
                            "duration": vdata["duration"],
                            "is_preview_free": vdata["preview"],
                            "player_url": vdata["url"],
                            "order": v_idx
                        }
                    )

            # Create Files
            for fdata in files_data:
                CourseFile.objects.get_or_create(
                    course=course,
                    title=fdata["title"],
                    defaults={"file_url": fdata["url"], "file_size": fdata["size"]}
                )

            # Create Sample Review
            Review.objects.get_or_create(
                course=course,
                student_name="Marcus Aurelius Sterling",
                defaults={
                    "student_title": "CEO, Sterling Logistics Group",
                    "rating": 5,
                    "comment": f"The frameworks in {course.name} added $1.2M to our bottom line within 90 days. Essential for any executive."
                }
            )

            # Give course access to the default admin user
            Enrollment.objects.get_or_create(
                user=admin_user,
                course=course,
                defaults={"source": "Admin"},
            )

        self.stdout.write(self.style.SUCCESS("Database seeding completed successfully!"))
