"""Shared setup for the audit scripts: import the topic modules read-only from the prime worktree."""
import os
import sys

REPO = "/root/Projects/trading-framework-prime"
if REPO not in sys.path:
    sys.path.insert(0, REPO)
os.chdir(REPO)

from src.notebooks.reports.topics.prime_academy.modules import prime as PA  # noqa: E402

SPLIT = 0.70
STOP0 = 34.791728647093755          # decision.json "stop"
SWAP_COIN = 0.004783927673690548    # decision.json side_share coin
G_COMM = PA.cost_share(STOP0, s=0.0)
G_SPREAD = PA.cost_share(STOP0)
G_COIN = G_SPREAD + SWAP_COIN
G_ASIDES = G_SPREAD * 2.33 + SWAP_COIN
PACE = 2.02508032004559             # front.json pace_rr at RR 1
T3 = PA.Tier(3000.0, 38.0, 51.0)


def pick(g, wait, lo=0.006, hi=0.020, step=0.00025, width=0.01):
    """Section 25's funded pick: line search, plateau within `width`, fewest median trades to the
    first payout, ties to the larger E[W]."""
    rows = PA.funded_line_search(g, lo=lo, hi=hi, step=step, wait=wait)
    plat = PA.plateau(rows, width=width)
    return min(plat, key=lambda r: (r["med_first_pay"], -r["e_W"])), rows


def cell(g, wait, rf=None, ra=0.03, pace=PACE, h=0.8):
    """Exact per-purchase quantities at assessment risk ra and funded risk rf (picked if None)."""
    if rf is None:
        rf = pick(g, wait)[0]["risk"]
    e = PA.eval_chain(ra, g * ra, rr=1.0, clip_up=True, clip_dn=True)
    f = PA.funded_chain(rf, g * rf, PA.payout_threshold(rf, 1.0, 3000, SPLIT), rr=1.0, clip_dn=True, wait=wait)
    cash = SPLIT * 3000 * e["p_pass"] * f["e_W"]
    days = pace * (e["e_trades"] + e["p_pass"] * f["e_life"])
    return dict(g=g, wait=wait, rf=rf, p_pass=e["p_pass"], e_nA=e["e_trades"], p_any=f["p_any"], e_W=f["e_W"],
                e_npay=f["e_npay"], e_life=f["e_life"], med_first_pay=f["med_first_pay"], cash_fee=cash / 38.0,
                G=(h * cash - 38.0) * 365 / days, cycle_days=days)


def wallet(g, wait, rf, n=5000, seed=None, h=0.8, horizon=541, ra=0.03, **kw):
    seed = 11 if seed is None else seed
    return PA.wallet_mc(T3, ra, g * ra, SPLIT, h, 1000, horizon_days=horizon, n=n, seed=seed, rr=1.0, wait=wait,
                        funded_risk=rf, funded_cost=g * rf, clip_up=True, clip_dn=True, paths=True, **kw)
