#!/usr/bin/env python3
"""
Extrator de lugares salvos do Google Maps
Suporta múltiplos formatos de entrada
"""

import json
import csv
import re
from pathlib import Path
from datetime import datetime

def extract_from_google_takeout(takeout_file):
    """
    Extrai lugares do arquivo JSON do Google Takeout
    Download em: https://takeout.google.com/settings/takeout
    Selecione: Maps (Seus locais) > Criar exportação
    """
    try:
        with open(takeout_file, 'r', encoding='utf-8') as f:
            data = json.load(f)

        places = []

        # Google Takeout formato: {"features": [...]}
        if 'features' in data:
            for feature in data['features']:
                props = feature.get('properties', {})
                geometry = feature.get('geometry', {})
                coords = geometry.get('coordinates', [])

                place = {
                    'name': props.get('Title', props.get('name', 'Unnamed')),
                    'address': props.get('Location', {}).get('Address', ''),
                    'latitude': coords[1] if len(coords) > 1 else None,
                    'longitude': coords[0] if len(coords) > 0 else None,
                    'comment': props.get('Comment', ''),
                    'url': props.get('Google Maps URL', ''),
                    'date': props.get('Published', ''),
                }
                places.append(place)

        # Google Maps "Saved Places" formato alternativo
        elif 'type' in data and data['type'] == 'FeatureCollection':
            for feature in data.get('features', []):
                props = feature.get('properties', {})
                coords = feature.get('geometry', {}).get('coordinates', [])

                place = {
                    'name': props.get('name', 'Unnamed'),
                    'address': props.get('address', ''),
                    'latitude': coords[1] if len(coords) > 1 else None,
                    'longitude': coords[0] if len(coords) > 0 else None,
                    'category': props.get('category', ''),
                }
                places.append(place)

        return places

    except Exception as e:
        print(f"❌ Erro ao ler arquivo: {e}")
        return []

def extract_from_csv(csv_file):
    """Extrai lugares de arquivo CSV exportado"""
    places = []
    try:
        with open(csv_file, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                place = {
                    'name': row.get('Title', row.get('Name', row.get('name', ''))),
                    'address': row.get('Address', row.get('address', '')),
                    'latitude': float(row.get('Latitude', row.get('latitude', 0))),
                    'longitude': float(row.get('Longitude', row.get('longitude', 0))),
                    'comment': row.get('Comment', row.get('Note', '')),
                    'url': row.get('URL', row.get('url', '')),
                }
                places.append(place)
    except Exception as e:
        print(f"❌ Erro ao ler CSV: {e}")
    return places

def extract_from_kml(kml_file):
    """Extrai lugares de arquivo KML (Google Earth)"""
    places = []
    try:
        with open(kml_file, 'r', encoding='utf-8') as f:
            content = f.read()

        # Extrair placemarks
        placemark_pattern = r'<Placemark>(.*?)</Placemark>'
        placemarks = re.findall(placemark_pattern, content, re.DOTALL)

        for pm in placemarks:
            name_match = re.search(r'<name>(.*?)</name>', pm)
            desc_match = re.search(r'<description>(.*?)</description>', pm)
            coords_match = re.search(r'<coordinates>(.*?)</coordinates>', pm)

            if coords_match:
                coords = coords_match.group(1).strip().split(',')
                place = {
                    'name': name_match.group(1) if name_match else 'Unnamed',
                    'address': desc_match.group(1) if desc_match else '',
                    'longitude': float(coords[0]) if len(coords) > 0 else None,
                    'latitude': float(coords[1]) if len(coords) > 1 else None,
                }
                places.append(place)

    except Exception as e:
        print(f"❌ Erro ao ler KML: {e}")
    return places

def convert_to_viewer_format(places):
    """Converte para formato do visualizador HTML"""
    organized = []

    for i, place in enumerate(places, 1):
        formatted = {
            'numero': i,
            'id': f"google-place-{i}",
            'nomes': [place.get('name', 'Unnamed')],
            'enderecos': [place.get('address', '')] if place.get('address') else [],
            'estabelecimentos': [place.get('category', '')] if place.get('category') else [],
            'servicos': [],
            'urls': [place.get('url', '')] if place.get('url') else [],
            'coordenadas': []
        }

        if place.get('latitude') and place.get('longitude'):
            formatted['coordenadas'].append({
                'latitude': place['latitude'],
                'longitude': place['longitude']
            })

        if place.get('comment'):
            formatted['nomes'].append(place['comment'])

        organized.append(formatted)

    return organized

def save_for_viewer(places, output_file):
    """Salva no formato do visualizador"""
    organized = convert_to_viewer_format(places)

    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(organized, f, indent=2, ensure_ascii=False)

    print(f"✅ Dados salvos em: {output_file}")
    return organized

def main():
    print("=" * 80)
    print("🗺️  EXTRATOR DE LUGARES SALVOS - GOOGLE MAPS")
    print("=" * 80)
    print("\n📥 COMO OBTER SEUS DADOS DO GOOGLE MAPS:\n")
    print("1️⃣  Acesse: https://takeout.google.com")
    print("2️⃣  Desmarque tudo e selecione apenas 'Maps (seus lugares)'")
    print("3️⃣  Clique em 'Próxima etapa' → 'Criar exportação'")
    print("4️⃣  Aguarde o email com o link de download")
    print("5️⃣  Extraia o arquivo .zip baixado")
    print("6️⃣  Localize o arquivo: Takeout/Maps/Saved Places.json")
    print("\n" + "=" * 80)

    # Procurar arquivos na pasta Downloads
    downloads = Path.home() / 'Downloads'
    possible_files = list(downloads.glob('**/Saved Places.json')) + \
                    list(downloads.glob('**/saved_places.json')) + \
                    list(downloads.glob('**/*saved*.json')) + \
                    list(downloads.glob('**/*maps*.json')) + \
                    list(downloads.glob('**/*.kml'))

    if possible_files:
        print(f"\n🔍 Arquivos encontrados em Downloads:\n")
        for i, file in enumerate(possible_files[:10], 1):
            print(f"   {i}. {file.name} ({file.stat().st_size // 1024} KB)")

        print(f"\n💡 Para processar um arquivo, execute:")
        print(f"   python3 {__file__} <caminho-do-arquivo>")
    else:
        print(f"\n⚠️  Nenhum arquivo do Google Maps encontrado em Downloads")

    # Verificar se arquivo foi passado como argumento
    import sys
    if len(sys.argv) > 1:
        input_file = Path(sys.argv[1])

        if not input_file.exists():
            print(f"\n❌ Arquivo não encontrado: {input_file}")
            return

        print(f"\n🔄 Processando: {input_file.name}\n")

        # Detectar tipo de arquivo e extrair
        places = []
        if input_file.suffix == '.json':
            places = extract_from_google_takeout(input_file)
        elif input_file.suffix == '.csv':
            places = extract_from_csv(input_file)
        elif input_file.suffix == '.kml':
            places = extract_from_kml(input_file)
        else:
            print(f"❌ Formato não suportado: {input_file.suffix}")
            return

        if places:
            print(f"✅ {len(places)} lugares extraídos!\n")

            # Salvar para o visualizador
            output_file = Path.home() / 'google_maps_places_organized.json'
            organized = save_for_viewer(places, output_file)

            # Mostrar amostra
            print(f"\n📋 AMOSTRA DOS LUGARES:\n")
            for place in places[:5]:
                print(f"   📍 {place['name']}")
                if place.get('address'):
                    print(f"      📮 {place['address']}")
                if place.get('latitude') and place.get('longitude'):
                    print(f"      🌍 {place['latitude']:.6f}, {place['longitude']:.6f}")
                print()

            print(f"=" * 80)
            print(f"\n🌐 PRÓXIMO PASSO:")
            print(f"   Acesse: http://localhost:8000/maps-saved-places-viewer.html")
            print(f"   O visualizador irá carregar automaticamente os dados!")
            print(f"\n   Via Tailscale: http://100.75.88.8:8000/maps-saved-places-viewer.html")
            print(f"=" * 80)
        else:
            print(f"❌ Nenhum lugar encontrado no arquivo")

    print()

if __name__ == '__main__':
    main()
