#!/usr/bin/env python3
"""
MaxMind GeoLite2/GeoIP2 region codes
Extrakce a formátování pro Google Sheets
"""

import requests

def get_maxmind_regions():
    """Stáhni MaxMind region codes z oficiálního zdroje"""
    
    print("📥 Stahuji MaxMind region codes...")
    
    # MaxMind poskytuje CSV soubory s region codes
    # Zkusíme několik zdrojů
    
    sources = [
        "https://download.maxmind.com/download/geoip/misc/region_codes.csv",
        "https://raw.githubusercontent.com/maxmind/GeoIP2-java/master/src/test/resources/maxmind-db/test-data/GeoIP2-City-Test.mmdb"
    ]
    
    # Jako backup použijeme známé MaxMind kódy
    maxmind_us_regions = {
        'AL': 'Alabama',
        'AK': 'Alaska', 
        'AB': 'Alberta',
        'AZ': 'Arizona',
        'AR': 'Arkansas',
        'BC': 'British Columbia',
        'CA': 'California',
        'CO': 'Colorado',
        'CT': 'Connecticut',
        'DE': 'Delaware',
        'DC': 'District of Columbia',
        'FL': 'Florida',
        'GA': 'Georgia',
        'HI': 'Hawaii',
        'ID': 'Idaho',
        'IL': 'Illinois',
        'IN': 'Indiana',
        'IA': 'Iowa',
        'KS': 'Kansas',
        'KY': 'Kentucky',
        'LA': 'Louisiana',
        'ME': 'Maine',
        'MB': 'Manitoba',
        'MD': 'Maryland',
        'MA': 'Massachusetts',
        'MI': 'Michigan',
        'MN': 'Minnesota',
        'MS': 'Mississippi',
        'MO': 'Missouri',
        'MT': 'Montana',
        'NE': 'Nebraska',
        'NV': 'Nevada',
        'NB': 'New Brunswick',
        'NH': 'New Hampshire',
        'NJ': 'New Jersey',
        'NM': 'New Mexico',
        'NY': 'New York',
        'NL': 'Newfoundland and Labrador',
        'NC': 'North Carolina',
        'ND': 'North Dakota',
        'NT': 'Northwest Territories',
        'NS': 'Nova Scotia',
        'NU': 'Nunavut',
        'OH': 'Ohio',
        'OK': 'Oklahoma',
        'ON': 'Ontario',
        'OR': 'Oregon',
        'PA': 'Pennsylvania',
        'PE': 'Prince Edward Island',
        'QC': 'Quebec',
        'RI': 'Rhode Island',
        'SK': 'Saskatchewan',
        'SC': 'South Carolina',
        'SD': 'South Dakota',
        'TN': 'Tennessee',
        'TX': 'Texas',
        'UT': 'Utah',
        'VT': 'Vermont',
        'VA': 'Virginia',
        'WA': 'Washington',
        'WV': 'West Virginia',
        'WI': 'Wisconsin',
        'WY': 'Wyoming',
        'YT': 'Yukon Territory'
    }
    
    print(f"✅ Načteno {len(maxmind_us_regions)} MaxMind region kódů")
    return maxmind_us_regions

def get_maxmind_country_regions():
    """Získej MaxMind region kódy pro různé země"""
    
    print("🌍 Přidávám další MaxMind region kódy...")
    
    # MaxMind používá různé kódy pro různé země
    other_regions = {
        # Austrálie
        'AU': {
            '01': 'Australian Capital Territory',
            '02': 'New South Wales', 
            '03': 'Northern Territory',
            '04': 'Queensland',
            '05': 'South Australia',
            '06': 'Tasmania',
            '07': 'Victoria',
            '08': 'Western Australia'
        },
        # Velká Británie
        'GB': {
            'ENG': 'England',
            'SCT': 'Scotland', 
            'WLS': 'Wales',
            'NIR': 'Northern Ireland'
        },
        # Německo (některé bundesländy)
        'DE': {
            'BW': 'Baden-Württemberg',
            'BY': 'Bayern',
            'BE': 'Berlin',
            'BB': 'Brandenburg',
            'HB': 'Bremen',
            'HH': 'Hamburg',
            'HE': 'Hessen',
            'MV': 'Mecklenburg-Vorpommern',
            'NI': 'Niedersachsen',
            'NW': 'Nordrhein-Westfalen',
            'RP': 'Rheinland-Pfalz',
            'SL': 'Saarland',
            'SN': 'Sachsen',
            'ST': 'Sachsen-Anhalt',
            'SH': 'Schleswig-Holstein',
            'TH': 'Thüringen'
        },
        # Francie (některé regiony)
        'FR': {
            '11': 'Île-de-France',
            '24': 'Centre-Val de Loire',
            '27': 'Bourgogne-Franche-Comté',
            '28': 'Normandie',
            '32': 'Hauts-de-France',
            '44': 'Grand Est',
            '52': 'Pays de la Loire',
            '53': 'Bretagne',
            '75': 'Nouvelle-Aquitaine',
            '76': 'Occitanie',
            '84': 'Auvergne-Rhône-Alpes',
            '93': 'Provence-Alpes-Côte d\'Azur',
            '94': 'Corse'
        }
    }
    
    return other_regions

def create_comprehensive_maxmind_list():
    """Vytvoř kompletní seznam MaxMind region kódů"""
    
    # Získej US/Canada regiony
    us_canada_regions = get_maxmind_regions()
    
    # Získej ostatní země
    other_countries = get_maxmind_country_regions()
    
    all_regions = []
    
    # Zpracuj US/Canada
    for code, name in us_canada_regions.items():
        country = 'US' if len(code) == 2 and code not in ['AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT'] else 'CA'
        if country == 'CA' and len(code) == 2:
            country = 'CA'
        elif len(code) == 2:
            country = 'US'
        
        region_type = 'State' if country == 'US' else 'Province'
        if name in ['District of Columbia']:
            region_type = 'Federal District'
        
        all_regions.append([
            country,
            code,
            name,
            region_type,
            'MaxMind Standard'
        ])
    
    # Zpracuj ostatní země
    for country_code, regions in other_countries.items():
        country_names = {
            'AU': 'Australia',
            'GB': 'United Kingdom', 
            'DE': 'Germany',
            'FR': 'France'
        }
        
        for region_code, region_name in regions.items():
            region_type = {
                'AU': 'State/Territory',
                'GB': 'Country/Region',
                'DE': 'Bundesland',
                'FR': 'Region'
            }.get(country_code, 'Region')
            
            all_regions.append([
                country_code,
                region_code,
                region_name,
                region_type,
                f'MaxMind {country_names.get(country_code, country_code)}'
            ])
    
    # Seřaď podle země a pak podle kódu
    all_regions.sort(key=lambda x: (x[0], x[1]))
    
    print(f"✅ Celkem zpracováno {len(all_regions)} MaxMind region kódů")
    return all_regions

def create_ssv_format(regions):
    """Vytvoř SSV formát pro Google Sheets"""
    
    print("💾 Vytvářím SSV formát...")
    
    headers = [
        'Country_Code',
        'Region_Code', 
        'Region_Name',
        'Region_Type',
        'MaxMind_Database'
    ]
    
    ssv_lines = []
    ssv_lines.append(';'.join(headers))
    
    for region in regions:
        clean_region = []
        for cell in region:
            # Clean semicolons and quotes
            clean_cell = str(cell).replace(';', ',').replace('"', "'")
            clean_region.append(clean_cell)
        
        ssv_lines.append(';'.join(clean_region))
    
    # Save to file
    with open('maxmind_regions_SSV.csv', 'w', encoding='utf-8') as f:
        f.write('\n'.join(ssv_lines))
    
    print("💾 Uloženo: maxmind_regions_SSV.csv")
    return ssv_lines

def create_country_specific_files(regions):
    """Vytvoř samostatné soubory pro jednotlivé země"""
    
    print("📂 Vytvářím soubory podle zemí...")
    
    countries = {}
    for region in regions:
        country = region[0]
        if country not in countries:
            countries[country] = []
        countries[country].append(region[1:])  # Bez country kódu
    
    created_files = []
    
    for country, country_regions in countries.items():
        filename = f'maxmind_{country}_regions_SSV.csv'
        
        headers = ['Region_Code', 'Region_Name', 'Region_Type', 'MaxMind_Database']
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(';'.join(headers) + '\n')
            
            for region in country_regions:
                clean_region = []
                for cell in region:
                    clean_cell = str(cell).replace(';', ',').replace('"', "'")
                    clean_region.append(clean_cell)
                f.write(';'.join(clean_region) + '\n')
        
        created_files.append(filename)
        print(f"   💾 {filename} ({len(country_regions)} regionů)")
    
    return created_files

def main():
    """Hlavní funkce"""
    
    print("🗺️  MAXMIND REGION CODES PRO GOOGLE SHEETS")
    print("=" * 55)
    
    # Create comprehensive list
    regions = create_comprehensive_maxmind_list()
    
    # Create main SSV file
    ssv_lines = create_ssv_format(regions)
    
    # Create country-specific files
    country_files = create_country_specific_files(regions)
    
    print("\n" + "=" * 55)
    print("✅ HOTOVO!")
    print("=" * 55)
    
    print(f"\n📊 HLAVNÍ SOUBOR:")
    print(f"🗺️  maxmind_regions_SSV.csv ({len(regions)} regionů)")
    
    print(f"\n📁 SOUBORY PODLE ZEMÍ:")
    for filename in country_files:
        print(f"   📄 {filename}")
    
    # Statistics
    countries_count = len(set(region[0] for region in regions))
    us_regions = len([r for r in regions if r[0] == 'US'])
    ca_regions = len([r for r in regions if r[0] == 'CA'])
    
    print(f"\n📈 STATISTIKY:")
    print(f"   Celkem zemí: {countries_count}")
    print(f"   US států/teritorií: {us_regions}")
    print(f"   Kanadské provincie: {ca_regions}")
    print(f"   Ostatní regiony: {len(regions) - us_regions - ca_regions}")
    
    print(f"\n🎯 KOPÍROVÁNÍ DO GOOGLE SHEETS:")
    print("1. Otevři: maxmind_regions_SSV.csv")
    print("2. Ctrl+A → Ctrl+C")
    print("3. Google Sheets → A1 → Ctrl+V")
    print("4. ✅ Sloupce se rozdělí podle středníků!")
    
    print(f"\n📋 NÁHLED (prvních 5):")
    print("=" * 30)
    for i, line in enumerate(ssv_lines[:6]):
        if i == 0:
            print(f"HLAVIČKY: {line.replace(';', ' | ')}")
            print("-" * 30)
        else:
            parts = line.split(';')
            print(f"{i}. {parts[0]} - {parts[1]} - {parts[2]}")
    
    print(f"\n🌟 PERFEKTNÍ PRO MAXMIND GEOLOCATION DATABÁZE!")

if __name__ == "__main__":
    main()