import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.db import transaction
from django.utils.text import slugify

from api.models import Profile, Opportunity, IntroductionRequest


class Command(BaseCommand):
    help = "Seed demo data: users, profiles, opportunities, and intro requests."

    def add_arguments(self, parser):
        parser.add_argument(
            "--reset",
            action="store_true",
            help="Delete existing demo data (profiles, opportunities, intro requests) before seeding",
        )
        parser.add_argument(
            "--users",
            type=int,
            default=6,
            help="Approx number of non-admin demo users to ensure exist (default: 6)",
        )

    @transaction.atomic
    def handle(self, *args, **options):
        reset = options["--reset"] if "--reset" in options else options.get("reset")
        target_users = max(1, int(options.get("users", 6)))

        if reset:
            IntroductionRequest.objects.all().delete()
            Opportunity.objects.all().delete()
            Profile.objects.all().delete()
            self.stdout.write(self.style.WARNING("Cleared Profiles, Opportunities, and IntroductionRequests."))

        # Ensure an admin user exists
        admin_user, created = User.objects.get_or_create(username="admin")
        if created:
            admin_user.set_password("admin123")
            admin_user.is_staff = True
            admin_user.is_superuser = True
            admin_user.email = "admin@example.com"
            admin_user.save()
            self.stdout.write(self.style.SUCCESS("Created superuser 'admin' (password: admin123)"))
        else:
            if not admin_user.is_staff or not admin_user.is_superuser:
                admin_user.is_staff = True
                admin_user.is_superuser = True
                admin_user.save(update_fields=["is_staff", "is_superuser"])

        # Demo usernames to create/ensure
        default_names = [
            "alice",
            "bob",
            "charlie",
            "diana",
            "eve",
            "frank",
            "grace",
            "heidi",
            "ivan",
            "judy",
        ]

        usernames = default_names[: target_users]
        created_users = 0
        ensured_users = []
        for i, uname in enumerate(usernames):
            user, u_created = User.objects.get_or_create(username=uname)
            if u_created:
                user.set_password("password123")
                # Make first user staff to access admin_frontend
                if i == 0:
                    user.is_staff = True
                user.email = f"{uname}@example.com"
                user.save()
                created_users += 1
            ensured_users.append(user)

        # Ensure Profiles for each non-admin user
        created_profiles = 0
        bios = [
            "Passionate about building products and communities.",
            "Full-stack developer and coffee enthusiast.",
            "Marketer focused on growth and analytics.",
            "Product designer who loves simplicity.",
            "Data scientist exploring ML and AI.",
            "Entrepreneur connecting people and ideas.",
        ]
        industries_list = [
            "Technology",
            "Finance",
            "Healthcare",
            "Education",
            "E-commerce",
            "Media",
        ]

        for idx, user in enumerate(ensured_users):
            profile, p_created = Profile.objects.get_or_create(
                user=user,
                defaults={
                    "bio": bios[idx % len(bios)],
                    "interests": ", ".join(random.sample(["AI", "Web", "Cloud", "UX", "Data", "DevOps"], 3)),
                    "industry": industries_list[idx % len(industries_list)],
                    "is_verified": idx % 2 == 0,
                },
            )
            # Also set taggit tags to mirror interests (best-effort)
            try:
                if profile and profile.interests:
                    tokens = [t.strip() for t in profile.interests.split(",") if t.strip()]
                    if tokens:
                        profile.tags.set(tokens, clear=True)
            except Exception:
                pass
            if p_created:
                created_profiles += 1

        # Ensure a few Opportunities
        opp_titles = [
            "Build Analytics Dashboard",
            "Launch Marketing Campaign",
            "Design Mobile App UI",
            "Migrate to Cloud Infrastructure",
            "Implement Recommendation Engine",
        ]
        created_opps = 0
        for title in opp_titles:
            opp, o_created = Opportunity.objects.get_or_create(
                title=title,
                defaults={
                    "description": f"Opportunity to {title.lower()}. Help wanted from motivated contributors.",
                },
            )
            if o_created:
                created_opps += 1

        # Ensure a few IntroductionRequests between different users
        created_intros = 0
        if len(ensured_users) >= 2:
            pairs = []
            for i in range(0, min(4, len(ensured_users) - 1)):
                a = ensured_users[i]
                b = ensured_users[-(i + 1)]
                if a != b:
                    pairs.append((a, b))
            for (a, b) in pairs:
                msg = f"Hi {b.username}, would love to connect about {random.choice(['AI', 'design', 'growth', 'data'])}."
                exists = IntroductionRequest.objects.filter(from_user=a, to_user=b, message=msg).exists()
                if not exists:
                    IntroductionRequest.objects.create(
                        from_user=a, to_user=b, message=msg, is_accepted=random.choice([False, True])
                    )
                    created_intros += 1

        self.stdout.write(
            self.style.SUCCESS(
                f"Seed complete: users(+{created_users}), profiles(+{created_profiles}), opportunities(+{created_opps}), intro_requests(+{created_intros})"
            )
        )
