"""Expected-value view of the purchase (exact chains, funded risk re-picked by the plateau rule only at the endpoints): cash per $38 fee as a function of the cost share,
and the cost share / spread / step-aside rate at which 80%-honoured expected cash equals the fee (EV breakeven) -- the criterion the log-growth gate is a noisy proxy for.
Also: breakeven honour rate by scenario."""
import numpy as np
from pa_imp import *
SW=0.004783927673690548; S0=PA.cost_share(34.791728647093755)       # commission+spread share at the mean stop
def cash_fee(g,rf=None,wait=7):
    e=PA.eval_chain(0.03,g*0.03,rr=1.0,clip_up=True,clip_dn=True)
    if rf is None:
        rows=PA.funded_line_search(g,lo=0.010,hi=0.020,step=0.0005,wait=wait)
        pk=min(PA.plateau(rows),key=lambda r:(r['med_first_pay'],-r['e_W'])); rf=pk['risk']
    f=PA.funded_chain(rf,g*rf,PA.payout_threshold(rf,1.0,3000,0.7),rr=1.0,clip_dn=True,wait=wait)
    return 0.7*3000*e['p_pass']*f['e_W']/38,e['p_pass'],f['p_any'],rf
print("cost share -> cash/fee (funded risk re-picked on a 0.05% grid), breakeven honour = 1/cash_fee")
res=[]
for A in (0.0,0.02,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,1.0,1.33):
    g=S0*(1+A)+SW
    cf,pp,pa,rf=cash_fee(g); res.append((A,g,cf))
    print(f"asides/trade {A:4.2f}: cost share {g:.4%}  pass {pp:.4f} any {pa:.4f} rf {rf:.4%}  cash/fee {cf:.4f}  breakeven honour {1/cf:.1%}  EV@80% {0.8*cf-1:+.3f} fees")
# spread flip for EV and for the log gate (gate flip share 3.41% from e05)
for s in (0.0,0.1,0.2,0.3,0.5,0.52,0.7,1.0,1.5):
    g=(0.5+s)/34.791728647093755+SW
    cf,pp,pa,rf=cash_fee(g)
    print(f"spread {s:4.2f} pip: cost share {g:.4%}  cash/fee {cf:.4f}  breakeven honour {1/cf:.1%}")
