"""Score a CSV of locations in batches of 500. DRY RUN by default: prints count and price, pays nothing.

    python 07_batch_csv.py places.csv weather            # dry run ($0.0002 per location)
    python 07_batch_csv.py places.csv weather --go       # PAID, needs GETFIXN_KEY
    python 07_batch_csv.py places.csv risk --go          # PAID, $0.05 per location

places.csv needs columns lat,lon and optionally label.
"""
import csv, sys
from gf import Client, PaymentRequired

path, kind = sys.argv[1], (sys.argv[2] if len(sys.argv) > 2 else "weather")
route, price = {"weather": ("/v1/weather/batch", 0.0002), "risk": ("/v1/portfolio/risk", 0.05)}[kind]
with open(path, newline="") as f:
    locs = [{"lat": float(r["lat"]), "lon": float(r["lon"]), "label": r.get("label", "")} for r in csv.DictReader(f)]
print(f"{len(locs)} locations x ${price} = ${len(locs) * price:.4f}")
if "--go" not in sys.argv:
    sys.exit("dry run only. Add --go to pay.")

c, out = Client(min_interval=1.0), []
for i in range(0, len(locs), 500):                       # 500 locations per call is the maximum
    body = {"locations": locs[i:i + 500], **({"window": "24h"} if kind == "risk" else {})}
    try:
        out += c.post(route, body)["results"]
    except PaymentRequired as e:
        sys.exit(f"Stopped at row {i}: {e}")
with open("results.csv", "w", newline="") as f:
    w = csv.writer(f); w.writerow(["lat", "lon", "grade_or_temp"])
    for r in out:
        w.writerow([r["lat"], r["lon"], r.get("grade") or (r.get("current") or {}).get("temperature_f")])
print("wrote results.csv:", len(out), "rows")
