#!/usr/bin/env python3
"""Precio actual de ZEC/USD (Kraken, API pública) -> price.json. Si falla, conserva el anterior."""
import json, os, sys, time, urllib.request

try:
    request = urllib.request.Request("https://api.kraken.com/0/public/Ticker?pair=ZECUSD", headers={"User-Agent": "zecradar/1.0"})
    with urllib.request.urlopen(request, timeout=15) as response:
        data = json.loads(response.read(65536))
    ticker = next(iter(data["result"].values()))
    last, day_open = float(ticker["c"][0]), float(ticker["o"])
    if data.get("error") or not (0 < last < 1e7 and 0 < day_open < 1e7):
        raise ValueError
except Exception:
    sys.exit("price.py: sin precio nuevo")
payload = json.dumps({"usd": last, "open_today_utc": day_open, "high_24h": float(ticker["h"][1]),
                      "low_24h": float(ticker["l"][1]), "at": int(time.time()), "source": "Kraken"})
path = sys.argv[1]
with open(path + ".tmp", "w") as handle:
    handle.write(payload)
os.chmod(path + ".tmp", 0o644)
os.replace(path + ".tmp", path)
