"""SN50 reference push client (~50 lines). pip install bittensor-wallet httpx numpy
Usage: python push_client.py https://synth.arbos.life/v1/submit <validator_ss58 from llm.txt> <hotkey_mnemonic_file> BTC
Sends one 1h forecast (naive GBM) for the next whole UTC minute.
"""
import gzip, hashlib, json, sys, time, uuid
from datetime import datetime, timezone

import httpx
import numpy as np
from bittensor_wallet import Keypair

url, validator, mnem_file, asset = sys.argv[1:5]
kp = Keypair.create_from_mnemonic(open(mnem_file).read().strip())
price = float(httpx.get("https://data-api.binance.vision/api/v3/ticker/price", params={"symbol": asset + "USDT"}).json()["price"])
T = int(time.time()) // 60 * 60 + 60
start = datetime.fromtimestamp(T, timezone.utc).isoformat()
steps = np.random.normal(0, 0.005 * np.sqrt(60 / 3600), size=(1000, 60))
paths = price * np.cumprod(np.hstack([np.ones((1000, 1)), 1 + steps]), axis=1)
paths = [[float(f"{p:.7e}") for p in row] for row in paths]  # <= 8 significant digits
ts = int(time.time() * 1000)
body = json.dumps({"v": 1, "netuid": 50,
                   "simulation_input": {"asset": asset, "start_time": start, "time_increment": 60,
                                        "time_length": 3600, "num_simulations": 1000},
                   "miner_timestamp_ms": ts, "simulation_output": [T, 60, *paths]}).encode()
u = str(uuid.uuid4())
msg = f"{hashlib.sha256(body).hexdigest()}.{u}.{ts}.{validator}"
headers = {
    "Epistula-Version": "2", "Epistula-Timestamp": str(ts), "Epistula-Uuid": u,
    "Epistula-Signed-By": kp.ss58_address, "Epistula-Signed-For": validator,
    "Epistula-Request-Signature": "0x" + kp.sign(msg.encode()).hex(),
    "X-Synth-Competition": "1h", "X-Synth-Start-Time": start,
    "Content-Type": "application/json", "Content-Encoding": "gzip",
}
r = httpx.post(url, content=gzip.compress(body), headers=headers, timeout=30)
print(r.status_code, r.text)
