#!/usr/bin/env python3
"""
Extrakce dat ze stránky GeoNames a převod do formátu pro Google Sheets
"""

import requests
from bs4 import BeautifulSoup
import csv
import re

def extract_countries_from_page():
    """Extrahuj data o zemích přímo ze stránky"""
    
    url = "https://www.geonames.org/countries/"
    
    try:
        print("📥 Stahuji data ze stránky GeoNames...")
        response = requests.get(url, timeout=30)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Najdi tabulku se zeměmi
        table = soup.find('table')
        if not table:
            print("❌ Tabulka nebyla nalezena")
            return None
        
        countries = []
        rows = table.find_all('tr')
        
        # Získej hlavičky z první řádky
        headers = []
        if rows:
            header_row = rows[0]
            for th in header_row.find_all(['th', 'td']):
                headers.append(th.get_text(strip=True))
        
        print(f"📋 Nalezené sloupce: {headers}")
        
        # Zpracuj data řádky
        for i, row in enumerate(rows[1:], 1):  # Skip header
            cells = row.find_all(['td', 'th'])
            if len(cells) >= 8:  # Minimum expected columns
                country_data = []
                for cell in cells:
                    text = cell.get_text(strip=True)
                    # Clean up text
                    text = re.sub(r'\s+', ' ', text)  # Replace multiple spaces
                    country_data.append(text)
                
                countries.append(country_data)
        
        print(f"✅ Extrahováno {len(countries)} zemí")
        return headers, countries
        
    except Exception as e:
        print(f"❌ Chyba při extrakci: {e}")
        return None

def save_for_google_sheets(headers, countries):
    """Ulož data ve formátu připraveném pro Google Sheets"""
    
    # TSV format (tab-separated) - nejlepší pro kopírování do Google Sheets
    tsv_file = "countries_for_sheets.tsv"
    
    with open(tsv_file, 'w', encoding='utf-8', newline='') as f:
        # Write headers
        f.write('\t'.join(headers) + '\n')
        
        # Write data
        for country in countries:
            # Ensure all fields are strings and clean
            clean_row = []
            for cell in country:
                if cell:
                    clean_cell = str(cell).replace('\t', ' ').replace('\n', ' ')
                    clean_row.append(clean_cell)
                else:
                    clean_row.append('')
            
            f.write('\t'.join(clean_row) + '\n')
    
    print(f"💾 Data uložena do {tsv_file}")
    
    # CSV format jako backup
    csv_file = "countries_for_sheets.csv"
    
    with open(csv_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(countries)
    
    print(f"💾 Backup CSV: {csv_file}")
    
    return tsv_file

def create_copy_paste_instructions():
    """Vytvoř instrukce pro kopírování do Google Sheets"""
    
    instructions = """
📋 NÁVOD PRO KOPÍROVÁNÍ DO GOOGLE SHEETS
==========================================

1. Otevři soubor: countries_for_sheets.tsv
   - Můžeš ho otevřít v textovém editoru nebo Excelu

2. Vybrat všechna data:
   - Ctrl+A (Windows/Linux) nebo Cmd+A (Mac)
   - Zkopíruj: Ctrl+C nebo Cmd+C

3. Jdi do své Google Sheets tabulky:
   - https://docs.google.com/spreadsheets/d/1b4GKYaRVh_V3dN4Ok01EiUHdpoQxr0a_6ptoSZWsj_o/

4. Klikni na buňku A1

5. Vlož data:
   - Ctrl+V nebo Cmd+V
   - Google Sheets automaticky rozdělí sloupce podle tabů

6. Formátování (volitelné):
   - Vyber první řádku (hlavičky)
   - Udělej ji tučnou: Ctrl+B
   - Zmraz první řádku: View → Freeze → 1 row

✅ Hotovo! Máš všechna data o zemích ve své tabulce.

ALTERNATIVA - přímé kopírování z konzole:
Spusť tento script a zkopíruj výstup níže označený "COPY THIS"
"""
    
    with open("copy_instructions.txt", 'w', encoding='utf-8') as f:
        f.write(instructions)
    
    print("📖 Instrukce uloženy do: copy_instructions.txt")

def main():
    """Hlavní funkce"""
    
    print("🌍 Extrakce dat o zemích pro Google Sheets")
    print("=" * 50)
    
    # Extract data
    result = extract_countries_from_page()
    if not result:
        print("❌ Extrakce selhala")
        return
    
    headers, countries = result
    
    # Save files
    tsv_file = save_for_google_sheets(headers, countries)
    create_copy_paste_instructions()
    
    print("\n" + "=" * 50)
    print("✅ HOTOVO!")
    print(f"📁 TSV soubor pro kopírování: {tsv_file}")
    print("📖 Přečti si: copy_instructions.txt")
    
    # Show preview
    print("\n📋 NÁHLED DAT (prvních 5 zemí):")
    print("=" * 50)
    
    print('\t'.join(headers))
    print("-" * 50)
    
    for i, country in enumerate(countries[:5]):
        print('\t'.join(str(cell) for cell in country))
    
    print(f"\n... a dalších {len(countries) - 5} zemí")
    
    print("\n🔄 PRO KOPÍROVÁNÍ:")
    print(f"1. Otevři soubor: {tsv_file}")
    print("2. Ctrl+A → Ctrl+C")
    print("3. Jdi do Google Sheets → A1 → Ctrl+V")

if __name__ == "__main__":
    main()