from django.core.management.base import BaseCommand
from django.apps import apps
from django.db import transaction

CommissionSplit = apps.get_model('commissions', 'CommissionSplit')


class Command(BaseCommand):
    help = "Fix Andhra Pradesh spelling in CommissionSplit model (Andhrapradesh -> Andhra Pradesh)"

    def add_arguments(self, parser):
        parser.add_argument(
            "--apply",
            action="store_true",
            help="Apply changes. Default = dry-run"
        )
        parser.add_argument(
            "--verbose",
            action="store_true",
            help="Show each updated row in output"
        )

    def handle(self, *args, **options):
        dry = not options["apply"]
        verbose = options["verbose"]

        wrong = "Andhrapradesh"
        correct = "Andhra Pradesh"

        qs = CommissionSplit.objects.filter(state__iexact=wrong)
        total = qs.count()

        self.stdout.write(f"Found {total} rows to fix.")
        if dry:
            self.stdout.write(self.style.WARNING("Dry-run: No changes will be saved."))

        changed = 0
        errors = []

        with transaction.atomic():
            for row in qs:
                orig = row.state
                row.state = correct

                if verbose:
                    self.stdout.write(f"ID {row.id}: '{orig}' -> '{correct}'")

                if not dry:
                    try:
                        row.save(update_fields=["state"])
                        changed += 1
                    except Exception as e:
                        errors.append(str(e))

            if dry:
                transaction.set_rollback(True)

        self.stdout.write(self.style.SUCCESS(f"Rows that would change: {total}"))
        if not dry:
            self.stdout.write(self.style.SUCCESS(f"Successfully updated: {changed}"))

        if errors:
            self.stdout.write(self.style.ERROR("Errors:"))
            for e in errors:
                self.stdout.write(self.style.ERROR(e))



# 🔧 How to Use It
# Dry Run (safe check)
# python manage.py fix_commission_state_names

# Dry Run + details
# python manage.py fix_commission_state_names --verbose

# Apply changes
# python manage.py fix_commission_state_names --apply

# Apply + details
# python manage.py fix_commission_state_names --apply --verbose