#!/usr/bin/env python3
import json, os, requests, ssl

OUT_DIR = "/data/news/images/0521"
os.makedirs(OUT_DIR, exist_ok=True)

with open("/data/news/json/0521data.json") as f:
    data = json.load(f)

ctx = ssl.create_default_context()

# brand_hotspots: brand_hotposts_{index}.jpg
for i, item in enumerate(data.get("brand_hotspots", [])):
    url = item.get("thumb", "").strip()
    if not url:
        continue
    fname = f"brand_hotposts_{i}.jpg"
    fpath = os.path.join(OUT_DIR, fname)
    if os.path.exists(fpath):
        print(f"  [skip] {fname} already exists")
        item["thumb"] = f"/images/0521/{fname}"
        continue
    try:
        r = requests.get(url, timeout=15, verify=False)
        with open(fpath, 'wb') as f:
            f.write(r.content)
        print(f"  [down] {fname} <- {url[:60]}...")
        item["thumb"] = f"/images/0521/{fname}"
    except Exception as e:
        print(f"  [err]  {fname}: {e}")

# vehicle_hotspots: vehicle_hotposts_{index}.jpg
for i, item in enumerate(data.get("vehicle_hotspots", [])):
    url = item.get("thumb", "").strip()
    if not url:
        continue
    fname = f"vehicle_hotposts_{i}.jpg"
    fpath = os.path.join(OUT_DIR, fname)
    if os.path.exists(fpath):
        print(f"  [skip] {fname} already exists")
        item["thumb"] = f"/images/0521/{fname}"
        continue
    try:
        r = requests.get(url, timeout=15, verify=False)
        with open(fpath, 'wb') as f:
            f.write(r.content)
        print(f"  [down] {fname} <- {url[:60]}...")
        item["thumb"] = f"/images/0521/{fname}"
    except Exception as e:
        print(f"  [err]  {fname}: {e}")

with open("/data/news/json/0521data.json", "w") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

print("\nDone. JSON updated.")