from django.core.management.base import BaseCommand
from noita.models import ObjectivPoint
from noita.services.decode import POINTS
from noita.services.spells import ALL_PERKS, ALL_SPELLS


class Command(BaseCommand):
    help = "Load ObjectivPoints from the POINTS dictionary in services.decode"

    def add_arguments(self, parser):
        parser.add_argument(
            "--clear",
            action="store_true",
            help="Clear all existing ObjectivPoints before loading",
        )

    def handle(self, *args, **options):
        if options["clear"]:
            ObjectivPoint.objects.all().delete()
            self.stdout.write(self.style.SUCCESS("Cleared existing ObjectivPoints"))

        created_count = 0
        updated_count = 0

        for objectiv_id, point_value in POINTS.items():
            # Skip special entries
            if objectiv_id in {"-", "DEBUG"}:
                continue

            # Get display string from objectiv_id (convert to title case)
            display_string = objectiv_id.replace("_", " ").title()

            # Create or update ObjectivPoint
            obj, created = ObjectivPoint.objects.get_or_create(
                objectiv_id=objectiv_id,
                defaults={
                    "display_string": display_string,
                    "point": point_value,
                    "max_count": 1,  # Default max_count is 1
                },
            )

            if created:
                created_count += 1
                self.stdout.write(f"✓ Created: {objectiv_id} - {point_value} points")
            else:
                # Update if points changed
                if obj.point != point_value or obj.display_string != display_string:
                    obj.point = point_value
                    obj.display_string = display_string
                    obj.save()
                    updated_count += 1
                    self.stdout.write(
                        self.style.WARNING(
                            f"↻ Updated: {objectiv_id} - {point_value} points"
                        )
                    )

        for op in ObjectivPoint.objects.filter(objectiv_id__in=ALL_SPELLS):
            op.display_string = f"Spell: {op.display_string}"
            op.save()

        for op in ObjectivPoint.objects.filter(objectiv_id__in=ALL_PERKS):
            op.display_string = f"Perk: {op.display_string}"
            op.save()

        for op in ObjectivPoint.objects.filter(objectiv_id__startswith="BOSS_KILL_"):
            b, k, c = op.display_string.split(" ")
            op.display_string = f"Perk: {op.display_string}"
            op.display_string = f"{b} {k} (with {c} orbs)"
            op.save()

        self.stdout.write(self.style.SUCCESS(f"\nCreated: {created_count}"))
        self.stdout.write(self.style.SUCCESS(f"Updated: {updated_count}"))
        self.stdout.write(
            self.style.SUCCESS(f"Total ObjectivPoints: {ObjectivPoint.objects.count()}")
        )
