"""Download and build country/region/city datasets for job location fields."""
from django.core.management.base import BaseCommand

from home.geo.build_cities_index import main as build_cities_index


class Command(BaseCommand):
    help = 'Build geo JSON files (countries, regions, cities) for location pickers'

    def handle(self, *args, **options):
        import json
        import urllib.request
        from pathlib import Path

        data_dir = Path(__file__).resolve().parents[2] / 'geo' / 'data'
        data_dir.mkdir(parents=True, exist_ok=True)
        base = (
            'https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/'
            'master/json'
        )

        self.stdout.write('Fetching countries...')
        with urllib.request.urlopen(f'{base}/countries.json', timeout=120) as response:
            countries = json.loads(response.read().decode())
        slim_countries = [{'code': item['iso2'], 'name': item['name']} for item in countries]
        (data_dir / 'countries.json').write_text(
            json.dumps(slim_countries, ensure_ascii=False),
            encoding='utf-8',
        )

        self.stdout.write('Fetching regions...')
        with urllib.request.urlopen(f'{base}/states.json', timeout=120) as response:
            states = json.loads(response.read().decode())
        regions_by_country = {}
        for state in states:
            code = state['country_code']
            regions_by_country.setdefault(code, []).append({
                'code': state.get('state_code') or state['name'],
                'name': state['name'],
            })
        (data_dir / 'regions_by_country.json').write_text(
            json.dumps(regions_by_country, ensure_ascii=False),
            encoding='utf-8',
        )

        self.stdout.write('Building cities index (may take a minute)...')
        build_cities_index()
        self.stdout.write(self.style.SUCCESS('Geo data build complete.'))
