#!/usr/bin/env python3
"""
Geocode all properties using their Locatie field and add coordinates to enriched_data.json
"""

import json
import time
import requests
from pathlib import Path

# Load enriched data
enriched_file = 'enriched_data.json'

if not Path(enriched_file).exists():
    print(f"❌ {enriched_file} not found. Please run custom_criteria.py first.")
    exit(1)

with open(enriched_file, 'r') as f:
    properties = json.load(f)

print(f"📊 Found {len(properties)} properties")

# Geocoding function
def geocode_location(location_name):
    """Geocode a location using Nominatim"""
    if not location_name or location_name == 'None':
        return None, None

    url = "https://nominatim.openstreetmap.org/search"
    params = {
        'q': location_name,
        'format': 'json',
        'limit': 1,
        'addressdetails': 1
    }
    headers = {'User-Agent': 'FarmMatch/1.0 (property analysis tool)'}

    try:
        response = requests.get(url, params=params, headers=headers, timeout=10)
        if response.status_code == 200:
            results = response.json()
            if results:
                return float(results[0]['lat']), float(results[0]['lon'])
    except Exception as e:
        print(f"   ⚠️  Error geocoding {location_name}: {e}")

    return None, None

# Geocode properties
geocoded_count = 0
already_have_coords = 0
failed_count = 0

for i, prop in enumerate(properties):
    location = prop.get('location', 'Unknown')

    # Check if already has coordinates
    if prop.get('lat') and prop.get('lon'):
        already_have_coords += 1
        if i % 20 == 0:
            print(f"   ⏭️  {i+1}/{len(properties)}: {location} (already has coords)")
        continue

    print(f"🌍 {i+1}/{len(properties)}: Geocoding {location}...")

    lat, lon = geocode_location(location)

    if lat and lon:
        prop['lat'] = lat
        prop['lon'] = lon
        geocoded_count += 1
        print(f"   ✅ Found: {lat:.4f}, {lon:.4f}")
    else:
        failed_count += 1
        print(f"   ❌ Failed to geocode")

    # Rate limiting - be nice to Nominatim
    time.sleep(1.1)

    # Save progress every 10 properties
    if (i + 1) % 10 == 0:
        with open(enriched_file, 'w') as f:
            json.dump(properties, f, indent=2)
        print(f"   💾 Progress saved ({geocoded_count} geocoded so far)")

# Final save
with open(enriched_file, 'w') as f:
    json.dump(properties, f, indent=2)

print("\n" + "="*60)
print("📍 GEOCODING COMPLETE")
print("="*60)
print(f"Already had coordinates: {already_have_coords}")
print(f"Newly geocoded: {geocoded_count}")
print(f"Failed to geocode: {failed_count}")
print(f"Total with coordinates: {already_have_coords + geocoded_count}/{len(properties)}")
print(f"\n✅ Updated {enriched_file}")
print("\nNow refresh the map viewer to see all properties!")
