import json
import os
import re
from django.core.files import File
from django.core.management.base import BaseCommand
from django.db import transaction
from api.models import *


class Command(BaseCommand):
    help = "Bulk create categories from images"

    def handle(self, *args, **kwargs):
        base_dir = "data/category"
        if not os.path.exists(base_dir):
            self.stdout.write(self.style.ERROR(f"Directory not found: {base_dir}"))
            return

        categories_to_create = []
        existing_names = set(Category.objects.values_list("description", flat=True))

        # Get all files
        files = [f for f in os.listdir(base_dir) if os.path.isfile(os.path.join(base_dir, f))]

        # Sort files based on leading number
        def sort_key(filename):
            match = re.match(r"(\d+)\.", filename)
            return int(match.group(1)) if match else float("inf")  # files without number go last

        files.sort(key=sort_key)

        for filename in files:
            file_path = os.path.join(base_dir, filename)

            # Remove extension
            description, _ = os.path.splitext(filename)

            # Remove leading number and dot, e.g., "1.apple" -> "apple"
            description = re.sub(r"^\d+\.\s*", "", description)

            if description in existing_names:
                continue  # skip existing

            with open(file_path, "rb") as f:
                category = Category(description=description.upper())
                category.image.save(filename, File(f), save=False)
                categories_to_create.append(category)

        # Bulk create
        with transaction.atomic():
            Category.objects.bulk_create(categories_to_create)

        self.stdout.write(self.style.SUCCESS(f"✅ Bulk created {len(categories_to_create)} categories."))

        craptitudes = []
        for i in Category.objects.all():
            for j in range(1, 11):
                craptitudes.append(Craptitude(category=i, roundNumber=j))

        Craptitude.objects.bulk_create(craptitudes, ignore_conflicts=True)
        self.stdout.write(self.style.SUCCESS(f"✅ Bulk created {len(craptitudes)} craptitudes."))

        for team in TeamName:
            Team.objects.create(name=team.value)
        self.stdout.write(self.style.SUCCESS(f"✅ Created {len(Team.objects.all())} teams."))

        plan_list = [
                {
                "name": "FREE ACCESS",
                "price": 0,
                "description": ["Access to Categories 1-5", "Basic features", "No credit card required"],
                "unlockCategory": 5,
                "type": PlanType.FREE_ACCESS,
                "productId": "free_access",
                "period": "FREE"
                },
                {
                "name": "BASIC PREMIUM",
                "price": 1.99,
                "description": ["Access to Categories 6-20", "15 additional categories", "Premium content access"],
                "unlockCategory": 20,
                "type": PlanType.BASIC_PREMIUM,
                "productId": "com.premium.crap.basic.yearly",
                "period": "YEAR"
                },
                {"name": "FULL ACCESS",
                "price": 3.99,
                "description": ["Access to ALL Categories (1-40)", "35 additional categories", "Complete premium content"],
                "unlockCategory": 40,
                "type": PlanType.FULL_ACCESS,
                "productId": "com.premium.crap.full.yearly",
                 "period": "YEAR"
                },
                ]
        for item in plan_list:
            Plan.objects.create(**item)
        self.stdout.write(self.style.SUCCESS(f"✅ Created plans successfully."))

        VERSION_DATA = [
            AppVersion(versionCode="1", deviceType=DeviceType.ANDROID),
            AppVersion(versionCode="1", deviceType=DeviceType.IOS)
        ]

        if AppVersion.objects.count() == 0:
            AppVersion.objects.bulk_create(VERSION_DATA, ignore_conflicts=True)

        self.stdout.write(self.style.SUCCESS(f"✅ Data seeded successfully."))

        json_file = 'data/prefixes.json'

        with open(json_file, "r") as f:
            data = json.load(f)

        for item in data:
            category_id = item["category"]
            round_number = item["craptitude"]

            craptitude, created = Craptitude.objects.update_or_create(
                category_id=category_id,
                roundNumber=round_number,
                defaults={
                    "diaperPrefix": item.get("diaperPrefix", ""),
                    "dumpsterPrefix": item.get("dumpsterPrefix", "")
                }
            )
        self.stdout.write(self.style.SUCCESS(f"✅ Added prefix in craptitude."))
