#!/usr/bin/env python3
import json
import sys
from pathlib import Path
import numpy as np

if len(sys.argv) != 2:
    print("usage: check_check_npz_sanity_v1.py path.npz", file=sys.stderr)
    sys.exit(2)

p = Path(sys.argv[1])
z = np.load(p, allow_pickle=True)

meta = {}
if "meta_json" in z.files:
    meta = json.loads(str(z["meta_json"]))

price = z["price"].astype(float)
input_usd = z["input_usd"].astype(float)

out = {
    "npz": str(p),
    "rows": int(price.size),
    "token0": meta.get("token0"),
    "token1": meta.get("token1"),
    "dec0": meta.get("dec0"),
    "dec1": meta.get("dec1"),
    "quote_token": meta.get("quote_token"),
    "fee_rate": meta.get("fee_rate"),
    "price_min": float(np.nanmin(price)),
    "price_max": float(np.nanmax(price)),
    "price_start": float(price[0]),
    "price_end": float(price[-1]),
    "input_usd_sum": float(np.nansum(input_usd)),
}
print(json.dumps(out, indent=2))

if out["rows"] < 50:
    print("[fatal] too few rows", file=sys.stderr)
    sys.exit(3)

if not (out["token0"] == "USDC" and out["token1"] == "CHECK"):
    print("[fatal] token order is not USDC/CHECK", file=sys.stderr)
    sys.exit(4)

if not (out["dec0"] == 6 and out["dec1"] == 18 and out["quote_token"] == "token0"):
    print("[fatal] decimals/quote token wrong", file=sys.stderr)
    sys.exit(5)

if not (0.000001 <= out["price_min"] <= out["price_max"] <= 10):
    print("[fatal] absurd CHECK price scale", file=sys.stderr)
    sys.exit(6)

if not (1 <= out["input_usd_sum"] <= 100_000_000):
    print("[fatal] absurd input_usd_sum", file=sys.stderr)
    sys.exit(7)

print("[ok] sanity pass")
