#!/usr/bin/env python3
"""
Monterey County, California weather station map with actual temperatures.
"""

import requests
import json
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed

# API endpoints
ALL_STATIONS_URL = "https://www.weatherlink.com/map/data"
STATION_DETAIL_URL = "https://www.weatherlink.com/map/data/station/{id}"

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
}

# Monterey County, California bounding box
MONTEREY_BOUNDS = {
    'min_lat': 35.78,
    'max_lat': 36.92,
    'min_lng': -121.98,
    'max_lng': -120.21
}

MAX_WORKERS = 5


def is_in_monterey(lat, lng):
    return (MONTEREY_BOUNDS['min_lat'] <= lat <= MONTEREY_BOUNDS['max_lat'] and
            MONTEREY_BOUNDS['min_lng'] <= lng <= MONTEREY_BOUNDS['max_lng'])


def get_temp_color(temp):
    """Get color for temperature value."""
    try:
        t = float(temp)
        if t < 0: return '#29333b'
        elif t < 10: return '#535f79'
        elif t < 20: return '#2f6695'
        elif t < 32: return '#1b7dbf'
        elif t < 40: return '#27a5af'
        elif t < 50: return '#00b58d'
        elif t < 60: return '#009247'
        elif t < 70: return '#fdd03b'
        elif t < 80: return '#ed9922'
        else: return '#dd5626'
    except:
        return '#888888'


def fetch_station_detail(station):
    """Fetch full details for a single station."""
    station_id = station.get('id')
    if not station_id:
        return None

    try:
        url = STATION_DETAIL_URL.format(id=station_id)
        resp = requests.get(url, headers=HEADERS, timeout=10)
        resp.raise_for_status()
        detail = resp.json()

        return {
            'lat': station.get('lat'),
            'lng': station.get('lng'),
            'name': detail.get('sStation', 'Unknown'),
            'temp': detail.get('temperature', '--'),
            'humidity': detail.get('humidity', '--'),
            'wind': detail.get('windSpeed', '--'),
            'wind_dir': detail.get('windDirection', '--'),
            'barometer': detail.get('barometer', '--'),
            'updated': detail.get('lastUpdatedAt', '--')
        }
    except:
        return None


def main():
    print("=" * 60)
    print("Monterey County Weather Map Generator")
    print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)

    # Fetch all stations
    print("\nFetching station list...")
    resp = requests.get(ALL_STATIONS_URL, headers=HEADERS, timeout=30)
    all_stations = resp.json()
    print(f"  Total worldwide: {len(all_stations):,}")

    # Filter to Monterey County
    monterey_stations = [s for s in all_stations
                         if is_in_monterey(s.get('lat', 0), s.get('lng', 0))]
    print(f"  Monterey County: {len(monterey_stations)}")

    if not monterey_stations:
        print("No stations found!")
        return

    # Poll stations in parallel
    print(f"\nPolling {len(monterey_stations)} stations...")
    stations = []

    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        futures = {executor.submit(fetch_station_detail, s): s for s in monterey_stations}
        for future in as_completed(futures):
            result = future.result()
            if result:
                stations.append(result)

    print(f"  Got data for {len(stations)} stations")

    if not stations:
        print("No station data retrieved!")
        return

    # Calculate stats
    temps = []
    for s in stations:
        try:
            temps.append(float(s['temp']))
        except:
            pass

    if temps:
        min_temp = min(temps)
        max_temp = max(temps)
        print(f"  Temp range: {min_temp:.0f}°F to {max_temp:.0f}°F")
    else:
        min_temp = max_temp = 0

    # Add colors to stations
    for s in stations:
        s['color'] = get_temp_color(s['temp'])

    # Generate HTML map
    html = f"""<!DOCTYPE html>
<html>
<head>
    <title>Monterey County Weather</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
        body {{ margin: 0; font-family: system-ui, -apple-system, sans-serif; }}
        #map {{ position: absolute; top: 0; bottom: 0; width: 100%; }}
        .info {{
            padding: 12px 16px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,.2);
        }}
        .info h3 {{ margin: 0 0 8px 0; }}
        .legend i {{
            display: inline-block;
            width: 18px;
            height: 18px;
            float: left;
            margin-right: 8px;
            border-radius: 3px;
        }}
    </style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([36.35, -121.1], 9);

L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{
    attribution: '© OpenStreetMap | Davis Instruments'
}}).addTo(map);

var stations = {json.dumps(stations)};

stations.forEach(function(s) {{
    var m = L.circleMarker([s.lat, s.lng], {{
        radius: 10,
        fillColor: s.color,
        color: '#fff',
        weight: 2,
        fillOpacity: 0.9
    }}).bindPopup(
        '<b>' + s.name + '</b><br>' +
        '🌡️ <b>' + s.temp + '°F</b><br>' +
        '💧 ' + s.humidity + '% humidity<br>' +
        '💨 ' + s.wind + ' mph ' + s.wind_dir + '<br>' +
        '📊 ' + s.barometer + ' in Hg<br>' +
        '<small>' + s.updated + '</small>'
    ).addTo(map);
    m.on('mouseover', function() {{ this.openPopup(); }});
    m.on('mouseout', function() {{ this.closePopup(); }});
}});

// Info box
var info = L.control({{ position: 'topright' }});
info.onAdd = function() {{
    var div = L.DomUtil.create('div', 'info');
    div.innerHTML = '<h3>🌡️ Monterey County, CA</h3>' +
        '<b>{len(stations)}</b> stations<br>' +
        '<small>Range: {min_temp:.0f}°F to {max_temp:.0f}°F</small><br>' +
        '<small>Updated: {datetime.now().strftime("%I:%M %p")}</small>';
    return div;
}};
info.addTo(map);

// Legend
var legend = L.control({{ position: 'bottomright' }});
legend.onAdd = function() {{
    var div = L.DomUtil.create('div', 'info legend');
    div.innerHTML = '<b>Temperature</b><br>' +
        '<i style="background:#27a5af"></i> 32-39°F<br>' +
        '<i style="background:#00b58d"></i> 40-49°F<br>' +
        '<i style="background:#009247"></i> 50-59°F<br>' +
        '<i style="background:#fdd03b"></i> 60-69°F<br>' +
        '<i style="background:#ed9922"></i> 70-79°F<br>' +
        '<i style="background:#dd5626"></i> 80°F+';
    return div;
}};
legend.addTo(map);
</script>
</body>
</html>"""

    # Save HTML
    output_file = "monterey_county_weather.html"
    with open(output_file, "w") as f:
        f.write(html)

    print(f"\n✓ Map saved to {output_file}")

    # Save station data
    with open("monterey_county_data.json", "w") as f:
        json.dump(stations, f, indent=2)
    print(f"✓ Data saved to monterey_county_data.json")

    print("=" * 60)


if __name__ == "__main__":
    main()
