#!/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_regime_decision_v1.py CHECK_FRESH.npz", file=sys.stderr)
    sys.exit(2)

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

ts = z["ts"].astype(np.int64)
price = z["price"].astype(float)

if len(price) < 100:
    print(json.dumps({"route": "idle", "reason": "too_few_rows", "rows": len(price)}, indent=2))
    sys.exit(0)

def last_window_return(hours):
    end_ts = ts[-1]
    start_ts = end_ts - int(hours * 3600)
    idx = np.searchsorted(ts, start_ts, side="left")
    idx = max(0, min(idx, len(price) - 1))
    return (price[-1] / price[idx] - 1.0) * 100.0

ret_24h = last_window_return(24)
ret_72h = last_window_return(72)
ret_7d = (price[-1] / price[0] - 1.0) * 100.0

# Simple DEMA helper
def ema(x, span):
    alpha = 2.0 / (span + 1.0)
    out = np.empty_like(x, dtype=float)
    out[0] = x[0]
    for i in range(1, len(x)):
        out[i] = alpha * x[i] + (1.0 - alpha) * out[i - 1]
    return out

# Use event rows, not bars. This is crude but enough for routing paper-live.
ema_fast = ema(price, 500)
ema_slow = ema(price, 2500)
trend_up = bool(ema_fast[-1] > ema_slow[-1])

# Conservative router:
# - wide only when trend and recent return agree.
# - otherwise tight, not idle, because tight is historically safer.
if trend_up and ret_72h > 8 and ret_24h > -5:
    route = "bull_wide_70_40_72h"
    strategy = "bull_wide_70_40_72h:70:40:72"
    reason = "bull_confirmed"
else:
    route = "tight_bear_85_0p5_336h"
    strategy = "tight_bear_85_0p5_336h:85:0.5:336"
    reason = "not_bull_or_uncertain"

out = {
    "npz": str(p),
    "rows": int(len(price)),
    "price_start": float(price[0]),
    "price_end": float(price[-1]),
    "ret_24h_pct": ret_24h,
    "ret_72h_pct": ret_72h,
    "ret_window_pct": ret_7d,
    "ema_fast_last": float(ema_fast[-1]),
    "ema_slow_last": float(ema_slow[-1]),
    "trend_up": trend_up,
    "route": route,
    "strategy": strategy,
    "reason": reason,
}
print(json.dumps(out, indent=2))
