# -*- coding: utf-8 -*-
"""抓取大区城市每日天气（open-meteo archive API，免 key）→ weather_city.json
结构：{城市: {yyyymmdd: {"t": 日均温℃, "r": 降水量mm}}}
增量逻辑：每城只补缺失日期；失败城市跳过不影响整体。供电费异动分析作辅助相关因素。"""
import json, os, sys, datetime, urllib.request, time

BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, "weather_city.json")

# 城市中心坐标（近似，±0.1° 对日级气温/降水足够）
COORD = {
    "三亚市": (18.25, 109.50), "三明市": (26.26, 117.64), "东山县": (23.70, 117.43),
    "东方市": (19.10, 108.65), "东莞市": (23.02, 113.75), "中山市": (22.52, 113.39),
    "云浮市": (22.93, 112.04), "云霄县": (23.96, 117.34), "佛山市": (23.02, 113.12),
    "儋州市": (19.52, 109.58), "南平市": (26.64, 118.18), "博罗县": (23.17, 114.29),
    "厦门市": (24.48, 118.09), "古田县": (26.58, 118.70), "四会市": (23.33, 112.73),
    "宁德市": (26.66, 119.52), "安溪县": (25.06, 118.18), "广宁县": (23.63, 112.44),
    "广州市": (23.13, 113.26), "德化县": (25.49, 118.24), "德庆县": (23.14, 111.79),
    "怀集县": (23.91, 112.19), "恩平市": (22.18, 112.31), "惠东县": (22.99, 114.72),
    "惠州市": (23.11, 114.42), "惠阳区": (22.79, 114.47), "揭阳市": (23.55, 116.37),
    "文昌市": (19.54, 110.75), "普宁市": (23.30, 116.17), "梅州市": (24.29, 116.12),
    "永泰县": (25.87, 118.94), "汕头市": (23.35, 116.68), "汕尾市": (22.79, 115.36),
    "江门市": (22.58, 113.08), "河源市": (23.74, 114.70), "泉州市": (24.87, 118.68),
    "泉港区": (25.12, 118.92), "海口市": (20.04, 110.34), "深圳市": (22.55, 114.06),
    "清远市": (23.68, 113.06), "湛江市": (21.27, 110.36), "漳州市": (24.51, 117.65),
    "漳浦县": (24.12, 117.61), "潮州市": (23.66, 116.62), "澄迈县": (19.74, 110.01),
    "珠海市": (22.27, 113.58), "琼海市": (19.26, 110.47), "福安市": (27.09, 119.65),
    "福州市": (26.07, 119.30), "罗源县": (26.49, 119.55), "肇庆市": (23.05, 112.47),
    "茂名市": (21.66, 110.93), "莆田市": (25.45, 119.01), "诏安县": (23.71, 117.18),
    "连江县": (26.19, 119.54), "闽清县": (26.22, 118.86), "阳江市": (21.86, 111.98),
    "陵水黎族自治县": (18.51, 110.04), "霞浦县": (26.89, 120.00), "韶关市": (24.81, 113.59),
    "饶平县": (23.66, 117.00), "龙岩市": (25.08, 117.02), "龙门县": (23.72, 114.26),
}

def fetch_city(lat, lon, d0, d1):
    url = (f"https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}"
           f"&start_date={d0}&end_date={d1}&daily=temperature_2m_mean,precipitation_sum"
           f"&timezone=Asia%2FShanghai")
    with urllib.request.urlopen(url, timeout=25) as resp:
        j = json.load(resp)
    dd = j.get("daily") or {}
    out = {}
    for i, t in enumerate(dd.get("time") or []):
        tm, pr = dd.get("temperature_2m_mean", [None])[i], dd.get("precipitation_sum", [None])[i]
        if tm is None and pr is None:
            continue
        out[t.replace("-", "")] = {"t": round(tm, 1) if tm is not None else None,
                                   "r": round(pr, 1) if pr is not None else None}
    return out

def main(days=31):
    data = json.load(open(OUT, encoding="utf-8")) if os.path.exists(OUT) else {}
    t1 = datetime.date.today() - datetime.timedelta(days=1)
    ok, fail = 0, []
    for city, (lat, lon) in COORD.items():
        have = data.get(city, {})
        want = [(t1 - datetime.timedelta(days=i)).strftime("%Y%m%d") for i in range(days)]
        miss = [d for d in want if d not in have]
        if not miss:
            ok += 1
            continue
        d0, d1 = min(miss), max(miss)
        iso = lambda s: f"{s[:4]}-{s[4:6]}-{s[6:]}"
        try:
            got = fetch_city(lat, lon, iso(d0), iso(d1))
            have.update({k: v for k, v in got.items() if k in want})
            data[city] = have
            ok += 1
        except Exception as e:
            fail.append(f"{city}: {e}")
        time.sleep(0.15)
    json.dump(data, open(OUT, "w", encoding="utf-8"), ensure_ascii=False)
    print(f"weather ok={ok} fail={len(fail)}", ("| " + "; ".join(fail[:5])) if fail else "")
    if fail and ok == 0:
        sys.exit(1)

if __name__ == "__main__":
    main(int(sys.argv[1]) if len(sys.argv) > 1 else 31)
