"""
Randomly set country=Pakistan and city (from a fixed PK list) on business profiles.

Skips the user with username `aizazusman` (case-insensitive).

Note: Only BusinessProfile rows have city/country in this project; influencer
accounts without a business profile are unchanged.
"""

import random

from django.core.management.base import BaseCommand

from businesses.models import BusinessProfile

CITIES = [
    'Karachi',
    'Rawalpindi',
    'Hyderabad',
    'Lahore',
    'Islamabad',
    'Peshawar',
    'Quetta',
]

EXCLUDE_USERNAME = 'aizazusman'


class Command(BaseCommand):
    help = (
        'Set country=Pakistan and a random PK city on all BusinessProfile rows '
        f'except user {EXCLUDE_USERNAME!r}.'
    )

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Print what would change without saving.',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        qs = BusinessProfile.objects.exclude(
            user__username__iexact=EXCLUDE_USERNAME,
        ).select_related('user')

        total = qs.count()
        if total == 0:
            self.stdout.write(self.style.WARNING('No business profiles to update.'))
            return

        self.stdout.write(f'Profiles to update: {total} (excluding {EXCLUDE_USERNAME})')

        if dry_run:
            for bp in qs[:20]:
                city = random.choice(CITIES)
                self.stdout.write(
                    f'  [dry-run] {bp.user.username}: city={city}, country=Pakistan'
                )
            if total > 20:
                self.stdout.write(f'  ... and {total - 20} more')
            self.stdout.write(self.style.WARNING('Dry run — no rows saved.'))
            return

        updated = 0
        for bp in qs:
            bp.country = 'Pakistan'
            bp.city = random.choice(CITIES)
            bp.save(update_fields=['country', 'city'])
            updated += 1

        self.stdout.write(self.style.SUCCESS(f'Updated {updated} business profile(s).'))
