"""The 14-calendar-day payout clock expressed in trades.  Paper/notebook: wait = round(14 / pace) = 7 trades, a constant.
Here: for every completed trade of the walker (deployed rule), m = the index of the first completed trade whose exit is >= 14 days after it
(the first moment a payout may be requested, counting that trade).  Compare the distribution of m with the constant 7; then the wallet at wait=7 vs m drawn from the empirical distribution."""
import numpy as np, pandas as pd
from walker import trades
from wallet_variants import *
T3=PA.Tier(3000,38,51); G0=PA.cost_share(34.791728647093755)+0.004783927673690548; RF=0.01575
ms=[]
for seed in range(1,6):
    d=trades(seed=seed); tout=d.t_out.to_numpy()/86400.0
    for k in range(len(tout)):
        j=np.searchsorted(tout,tout[k]+14.0,side='left')
        if j<len(tout): ms.append(j-k)         # trades k+1..j  => j-k trades up to and including the first exit >= 14 d
ms=np.array(ms)
vals,cnt=np.unique(ms,return_counts=True); p=cnt/cnt.sum()
print("m distribution (trades up to the first exit >= 14 days after the funding trade):",dict(zip(vals.tolist(),np.round(p,3).tolist())))
print(f"mean m {ms.mean():.2f}, median {np.median(ms):.0f}, share <=7 {np.mean(ms<=7):.2f}; 14/pace(2.108) = {14/2.108:.2f}")
# chain p_any mixture
pa=0; cf=0
e=PA.eval_chain(0.03,G0*0.03,rr=1.0,clip_up=True,clip_dn=True)
for v,pp in zip(vals,p):
    f=PA.funded_chain(RF,G0*RF,PA.payout_threshold(RF,1.0,3000,0.7),rr=1.0,clip_dn=True,wait=int(v))
    pa+=pp*f['p_any']; cf+=pp*0.7*3000*e['p_pass']*f['e_W']/38
f7=PA.funded_chain(RF,G0*RF,PA.payout_threshold(RF,1.0,3000,0.7),rr=1.0,clip_dn=True,wait=7)
print(f"p_any: constant 7 -> {f7['p_any']:.4f}; mixture over m -> {pa:.4f};   cash/fee: constant 7 -> {0.7*3000*e['p_pass']*f7['e_W']/38:.4f}; mixture -> {cf:.4f}")
for tag,kw in (("constant wait 7",dict(wait=7)),("constant wait 8",dict(wait=8)),("m drawn per cycle from the empirical distribution",dict(wait_dist=(vals,p)))):
    out=[]
    for seed in (13,14,15):
        w,ru,pu=wallet_var(T3,0.03,G0*0.03,0.7,0.8,1000,horizon_days=541,n=5000,seed=seed,funded_risk=RF,funded_cost=G0*RF,**kw)
        out.append(glog(w,1000)[0])
    print(f"{tag:55s}: e_log_growth(80%) by seed {np.round(out,4)} mean {np.mean(out):+.4f}")
