#!/usr/bin/env python3
"""
Jednoduchá extrakce dat ze stránky GeoNames pro Google Sheets
Bez dalších závislostí - použije pouze requests a regex
"""

import requests
import re
import csv

def extract_country_data():
    """Extrahuj data ze stránky pomocí regex"""
    
    url = "https://www.geonames.org/countries/"
    
    try:
        print("📥 Stahuji data z GeoNames...")
        response = requests.get(url, timeout=30)
        response.raise_for_status()
        
        html = response.text
        
        # Najdi tabulku - hledej pattern mezi <table> a </table>
        table_match = re.search(r'<table[^>]*>(.*?)</table>', html, re.DOTALL | re.IGNORECASE)
        
        if not table_match:
            print("❌ Tabulka nenalezena")
            return None
        
        table_html = table_match.group(1)
        
        # Extrahuj řádky tabulky
        rows = re.findall(r'<tr[^>]*>(.*?)</tr>', table_html, re.DOTALL | re.IGNORECASE)
        
        countries_data = []
        headers = None
        
        for i, row in enumerate(rows):
            # Extrahuj buňky (th nebo td)
            cells = re.findall(r'<t[hd][^>]*>(.*?)</t[hd]>', row, re.DOTALL | re.IGNORECASE)
            
            if not cells:
                continue
            
            # Vyčisti HTML tagy a entity
            clean_cells = []
            for cell in cells:
                # Odstraň HTML tagy
                clean_cell = re.sub(r'<[^>]+>', '', cell)
                # Dekóduj HTML entity
                clean_cell = clean_cell.replace('&amp;', '&')
                clean_cell = clean_cell.replace('&lt;', '<')
                clean_cell = clean_cell.replace('&gt;', '>')
                clean_cell = clean_cell.replace('&nbsp;', ' ')
                # Vyčisti whitespace
                clean_cell = re.sub(r'\s+', ' ', clean_cell).strip()
                clean_cells.append(clean_cell)
            
            if i == 0:
                # První řádek = hlavičky
                headers = clean_cells
                print(f"📋 Hlavičky: {headers}")
            else:
                if len(clean_cells) >= 8:  # Minimální počet sloupců
                    countries_data.append(clean_cells)
        
        print(f"✅ Extrahováno {len(countries_data)} zemí")
        return headers, countries_data
        
    except Exception as e:
        print(f"❌ Chyba: {e}")
        return None

def create_tsv_for_sheets(headers, countries):
    """Vytvoř TSV soubor pro kopírování do Google Sheets"""
    
    tsv_content = []
    
    # Headers
    if headers:
        tsv_content.append('\t'.join(headers))
    
    # Data rows
    for country in countries:
        # Ensure consistent number of columns
        row = []
        for i, cell in enumerate(country):
            if i < len(headers) if headers else 20:  # Limit columns
                row.append(str(cell) if cell else '')
        
        # Fill missing columns
        while len(row) < (len(headers) if headers else 9):
            row.append('')
        
        tsv_content.append('\t'.join(row))
    
    # Save to file
    with open('countries_ready_to_copy.tsv', 'w', encoding='utf-8') as f:
        f.write('\n'.join(tsv_content))
    
    return tsv_content

def main():
    """Hlavní funkce"""
    
    print("🌍 JEDNODUCHÉ KOPÍROVÁNÍ DAT O ZEMÍCH")
    print("=" * 50)
    
    # Extract data
    result = extract_country_data()
    
    if not result:
        print("❌ Extrakce selhala")
        return
    
    headers, countries = result
    
    # Create TSV for copying
    tsv_content = create_tsv_for_sheets(headers, countries)
    
    print("\n" + "=" * 50)
    print("✅ DATA PŘIPRAVENA PRO KOPÍROVÁNÍ!")
    print("=" * 50)
    
    print("\n📋 COPY-PASTE INSTRUKCE:")
    print("1. Zkopíruj text níže (včetně hlaviček)")
    print("2. Jdi do Google Sheets tabulky")
    print("3. Klikni na buňku A1")  
    print("4. Ctrl+V (vložit)")
    print("5. Google Sheets automaticky rozdělí sloupce")
    
    print("\n" + "="*20 + " COPY THIS " + "="*20)
    
    # Print first few rows as preview
    print("📋 NÁHLED (prvních 5 řádků):")
    for i, line in enumerate(tsv_content[:6]):  # Header + 5 rows
        print(line)
        if i == 0:
            print("-" * 80)
    
    print(f"\n... a dalších {len(tsv_content) - 6} zemí")
    
    print("\n💾 Úplná data uložena do: countries_ready_to_copy.tsv")
    print("📖 Můžeš otevřít soubor a zkopírovat vše (Ctrl+A, Ctrl+C)")
    
    print("\n" + "="*50)
    print("🎯 RYCHLÉ KOPÍROVÁNÍ:")
    print("Otevři countries_ready_to_copy.tsv → Ctrl+A → Ctrl+C → Google Sheets A1 → Ctrl+V")

if __name__ == "__main__":
    main()