"""Read the cached broker-map replays (no replay is run). Checks:
  a. the payout clock the broker used: trades since funding at the first payout,
  b. calendar days per trade in assessment against funded cells at RR 1 (the pace the 7-trade
     clock is converted with comes from assessment cells only),
  c. the days quoted in the paper's answer table (21 to pass, 46 to the first payout, 123 life).
"""
import json
from pathlib import Path

import numpy as np

CACHE = Path("/root/Projects/trading-framework-prime/src/notebooks/reports/_cache/prime_academy/broker_map")


def kv(line):
    return {k: v for k, v in (t.split("=", 1) for t in line.split()[1:] if "=" in t)}


def parse(lines):
    ev, fu, pays = [], [], []
    for l in lines:
        d = kv(l)
        if l.startswith("PAY"):
            pays.append(dict(eq=float(d["eq"]), trades=int(float(d["trades"])), since=int(float(d["since"])), secs=float(d["secs"])))
        elif d["stage"] == "EVAL":
            ev.append(dict(end=d["end"], trades=int(float(d["trades"])), secs=float(d["secs"])))
        else:
            fu.append(dict(end=d["end"], trades=int(float(d["trades"])), secs=float(d["secs"]), pays=pays))
            pays = []
    return ev, fu


def cell(kind, rr, ra, rf):
    return json.loads((CACHE / f"{kind}_rr{rr:g}_ra{100*ra:g}_rf{100*rf:g}.json").read_text())


for rr in (1.0,):
    for kind, r in (("eval", 0.03), ("eval", 0.04), ("funded", 0.015), ("funded", 0.01), ("funded", 0.02)):
        res = cell(kind, rr, r, r)
        tr, secs, first_trades, first_days, since, pays_eq = 0, 0.0, [], [], [], []
        for s in res["coin"].values():
            ev, fu = parse(s["lines"])
            acc = ev if kind == "eval" else fu
            tr += sum(a["trades"] for a in acc); secs += sum(a["secs"] for a in acc)
            for f in (fu if kind == "funded" else []):
                if f["pays"]:
                    first_trades.append(f["pays"][0]["trades"]); first_days.append(f["pays"][0]["secs"] / 86400)
                since += [p["since"] for p in f["pays"]]
                pays_eq += [p["eq"] for p in f["pays"]]
        line = f"{kind:6} RR {rr} r {r:.1%}: calendar days per trade {secs / 86400 / tr:.3f} over {tr} trades"
        if kind == "funded":
            line += (f"; first payout at trade: min {min(first_trades)}, median {np.median(first_trades):.0f}; "
                     f"trades since last payout at a payout: min {min(since)}; median days to first payout {np.median(first_days):.0f}; "
                     f"payout equity min {min(pays_eq):.4f} (minimum request {100/0.7/3000:.4f})")
        print(line)
