#!/usr/bin/env python3
"""PAPER ONLY - Windows-side refresh for the Kronos paper futures dashboard (accounts A, B and S). Python 3 stdlib only, no keys, no orders.

How it works (option chosen): the box runs the Kronos forecasts and the paper trade loop and is the only source of truth for
trades. It exports box_data.json. This script reads box_data.json (copy a fresh one over from the box whenever you like),
pulls live Hyperliquid mid prices, and re-marks the OPEN positions (mark, uPnL, equity, week-to-date open uPnL).
It never opens/closes trades; if a mark is through a stop/target it only flags it - the box loop does the fill on candles.
Writes dashboard_data.json next to dashboard.html."""
import json, os, sys, time, urllib.request
from datetime import datetime, timezone, timedelta

BASE = os.path.dirname(os.path.abspath(__file__)); ICT = timezone(timedelta(hours=7))
SRC = os.path.join(BASE, "box_data.json"); OUT = os.path.join(BASE, "dashboard_data.json")


def mids():
    req = urllib.request.Request("https://api.hyperliquid.xyz/info", data=b'{"type":"allMids"}',
                                 headers={"Content-Type": "application/json", "User-Agent": "kronos-paper-dash/1.0"})
    with urllib.request.urlopen(req, timeout=20) as r: return {k: float(v) for k, v in json.load(r).items()}


def main():
    if not os.path.exists(SRC): print("box_data.json missing - copy it from the box"); return 1
    d = json.load(open(SRC, encoding="utf-8"))
    try: m = mids()
    except Exception as e:
        print("HL mids fetch failed, showing box snapshot:", e); json.dump(d, open(OUT, "w", encoding="utf-8")); return 0
    for key in ("live", "live_b", "live_s", "live_c"):   # A (v1), B (v1b_widestop), S (v1s_scalp, paused), C (v1c_composite)
        remark(d.get(key), m)
    d["marks_refreshed_ict"] = datetime.now(ICT).strftime("%H:%M ICT")
    json.dump(d, open(OUT + ".tmp", "w", encoding="utf-8")); os.replace(OUT + ".tmp", OUT)
    print("refreshed marks (A+B+S+C)", d["marks_refreshed_ict"], {k: m.get(k) for k in ("BTC", "ETH", "HYPE")}); return 0


def remark(L, m):
    if L:
        now = time.time() * 1000; tot = 0.0
        for p in L.get("positions", []):
            if p["coin"] not in m: continue
            p["mark"] = m[p["coin"]]; sgn = 1 if p["side"] == "LONG" else -1
            p["upnl"] = sgn * (p["mark"] - p["entry"]) * p["notional"] / p["entry"] - p["entry_fee"] - p["funding"]
            p["hours_open"] = (now - datetime.strptime(p["since_ict"], "%Y-%m-%d %H:%M").replace(tzinfo=ICT).timestamp() * 1000) / 3.6e6
            through = (sgn > 0 and p["mark"] <= p["stop"]) or (sgn < 0 and p["mark"] >= p["stop"])
            hit_t = (sgn > 0 and p["mark"] >= p["target"]) or (sgn < 0 and p["mark"] <= p["target"])
            p["flag"] = "mark through STOP (box loop fills on candles)" if through else "mark through TARGET" if hit_t else ""
            tot += p["upnl"]
        if "cash" in L: L["equity_now"] = L["cash"] + tot
        if "wtd" in L: L["wtd"]["open_upnl"] = tot


if __name__ == "__main__":
    sys.exit(main())
