"""
Set audience_top_countries / audience_top_cities on influencer profiles.

- Country: Pakistan (100%) in audience_top_countries.
- Cities: random subset of Karachi, Rawalpindi, Hyderabad, Lahore, Islamabad,
  Peshawar, Quetta with percentages that sum to 100.

Skips user aizazusman (case-insensitive). Refreshes audience_summary_string
from structured fields when possible.
"""

import random

from django.core.management.base import BaseCommand

from influencers.models import InfluencerProfile
from influencers.services.data_helpers import rebuild_audience_summary_from_structured

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

EXCLUDE_USERNAME = 'aizazusman'


def _random_city_distribution(rng: random.Random) -> list:
    """1–3 distinct cities with percentages summing to ~100."""
    k = rng.randint(1, min(3, len(CITIES)))
    chosen = rng.sample(CITIES, k)
    if k == 1:
        return [{'name': chosen[0], 'percentage': 100.0}]
    raw = [rng.random() for _ in range(k)]
    s = sum(raw)
    pcts = [round(x / s * 100, 2) for x in raw]
    diff = round(100.0 - sum(pcts), 2)
    pcts[-1] = round(pcts[-1] + diff, 2)
    return [{'name': c, 'percentage': p} for c, p in zip(chosen, pcts)]


class Command(BaseCommand):
    help = (
        'Set audience_top_countries (Pakistan) and random PK audience_top_cities '
        f'for all influencer profiles except {EXCLUDE_USERNAME!r}.'
    )

    def add_arguments(self, parser):
        parser.add_argument(
            '--seed',
            type=int,
            default=None,
            help='Optional RNG seed for reproducible city splits.',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Print planned changes without saving.',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        seed = options['seed']
        rng = random.Random(seed)

        qs = InfluencerProfile.objects.exclude(
            user__username__iexact=EXCLUDE_USERNAME,
        ).select_related('user')

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

        countries = [{'name': 'Pakistan', 'percentage': 100.0}]

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

        if dry_run:
            for profile in qs[:15]:
                cities = _random_city_distribution(rng)
                self.stdout.write(
                    f'  [dry-run] @{profile.instagram_handle}: '
                    f'countries={countries} cities={cities}'
                )
            if total > 15:
                self.stdout.write(f'  ... and {total - 15} more')
            self.stdout.write(self.style.WARNING('Dry run — no rows saved.'))
            return

        updated = 0
        for profile in qs:
            profile.audience_top_countries = countries
            profile.audience_top_cities = _random_city_distribution(rng)
            rebuild_audience_summary_from_structured(profile)
            profile.save(
                update_fields=[
                    'audience_top_countries',
                    'audience_top_cities',
                    'audience_summary_string',
                ]
            )
            updated += 1

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