"""The strict reading of the 5% daily rule (open profit at the day boundary counts) through the
assessment chain. A losing trade from equity s dies with probability q_l(r), the share of losing
trades whose float at a day boundary exceeded (5% - r (1 + gamma)) / r of the stop (s04 trades,
EURUSD hourly, deployed stop). Everything else is prime.eval_chain with both clips.

Question: does it move the pass rate at 3%, and does a lower assessment risk then beat 3%?"""
import numpy as np
import pandas as pd

from common import PA, G_COIN

T = pd.read_csv("/tmp/arena-prime-audit/candidate-1/out_s04_trades.csv")
stops = T[T.why == "STOP"]


def q_loss(r, col):
    thr = (0.05 - r * (1 + G_COIN)) / r
    return float(np.mean(stops[col] > thr))


def eval_chain_breach(risk, cost, q, rr=1.0, target=PA.TARGET, dd=PA.MAXDD, nmax=20_000, tol=1e-12):
    """prime.eval_chain with clip_up and clip_dn, and a losing trade that dies with probability q."""
    units = PA._units(cost, None)
    Tt, D = int(round(target * units)), int(round(dd * units))
    R, C = int(round(risk * units)), int(round(cost * units))
    st = np.arange(-D + 1, Tt)
    a, b, p = PA._legs(st, R, rr, C, Tt, D, True, True)
    up, dn = st + a - C, st - b - C
    exit_up, exit_dn = up >= Tt, dn <= -D
    iu, idn = np.clip(up - st[0], 0, len(st) - 1), np.clip(dn - st[0], 0, len(st) - 1)
    v = np.zeros(len(st)); v[-st[0]] = 1.0
    P, n_tr = 0.0, 0.0
    for t in range(1, nmax):
        w, l = v * p, v * (1.0 - p) * (1.0 - q)          # the breached share of the losses leaves
        P += w[exit_up].sum()
        n_tr += v.sum()
        v = np.bincount(iu[~exit_up], w[~exit_up], len(st)) + np.bincount(idn[~exit_dn], l[~exit_dn], len(st))
        if v.sum() < tol:
            break
    return P, n_tr


print("risk   q_l(00 UTC) q_l(21 UTC) | pass: no breach   00 UTC    21 UTC   | trades")
for r in (0.02, 0.025, 0.0275, 0.03, 0.0315):
    q0, q21 = q_loss(r, "bf"), q_loss(r, "bf21")
    base = PA.eval_chain(r, G_COIN * r, rr=1.0, clip_up=True, clip_dn=True)
    p0, _ = eval_chain_breach(r, G_COIN * r, q0)
    p21, _ = eval_chain_breach(r, G_COIN * r, q21)
    print(f"{r:.2%}   {q0:8.2%}   {q21:8.2%}   |      {base['p_pass']:.2%}    {p0:.2%}   {p21:.2%}  | {base['e_trades']:.1f}")
