"""
Production data fetcher — pulls REAL historical/forecast weather for the
orchard regions from Open-Meteo (free, no API key required).

NOTE: this script needs outbound internet access. It could not be run
inside the sandboxed environment used to build this project (egress is
restricted to package registries there), but it is fully functional on
a normal machine / server. Use it to replace `simulate_weather()` with
real data, or to feed the soil-water-balance simulator with real
rainfall/temperature instead of the synthetic season curve.

Usage:
    python3 fetch_open_weather.py --start 2024-04-01 --end 2024-10-31
"""
import argparse
import requests
import pandas as pd

from master_data import REGIONS

# Coordinates for each region (Shopian, Anantnag, Pulwama, Baramulla, Shimla, Kullu)
REGION_COORDS = {
    1: (33.7157, 74.8320),  # Shopian
    2: (33.7311, 75.1487),  # Anantnag
    3: (33.8710, 74.8930),  # Pulwama
    4: (34.2090, 74.3436),  # Baramulla
    5: (31.1048, 77.1734),  # Shimla
    6: (31.9576, 77.1095),  # Kullu
}

ARCHIVE_URL = "https://archive-api.open-meteo.com/v1/archive"
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"

DAILY_VARS = [
    "temperature_2m_max", "temperature_2m_min", "temperature_2m_mean",
    "precipitation_sum", "relative_humidity_2m_mean",
    "shortwave_radiation_sum", "wind_speed_10m_max",
]


def fetch_region_weather(region_id: int, start: str, end: str, use_forecast_api: bool = False) -> pd.DataFrame:
    lat, lon = REGION_COORDS[region_id]
    url = FORECAST_URL if use_forecast_api else ARCHIVE_URL
    params = {
        "latitude": lat, "longitude": lon,
        "start_date": start, "end_date": end,
        "daily": ",".join(DAILY_VARS),
        "timezone": "Asia/Kolkata",
    }
    resp = requests.get(url, params=params, timeout=30)
    resp.raise_for_status()
    data = resp.json()["daily"]
    df = pd.DataFrame(data)
    df["region_id"] = region_id
    df["region_name"] = REGIONS[region_id]["name"]
    return df


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--start", default="2024-04-01")
    ap.add_argument("--end", default="2024-10-31")
    ap.add_argument("--out", default="../data/real_open_meteo_weather.csv")
    args = ap.parse_args()

    frames = []
    for region_id in REGIONS:
        print(f"Fetching real weather for region {region_id} ({REGIONS[region_id]['name']})...")
        try:
            frames.append(fetch_region_weather(region_id, args.start, args.end))
        except Exception as e:
            print(f"  failed: {e}")

    if frames:
        out = pd.concat(frames, ignore_index=True)
        out.to_csv(args.out, index=False)
        print(f"Saved {len(out)} rows to {args.out}")
    else:
        print("No data fetched. Check network access to archive-api.open-meteo.com")


if __name__ == "__main__":
    main()
