import sys; sys.path.insert(0,".")
import numpy as np, pandas as pd
from scripts.analysis.combine_portfolio import IDX, SPLIT, INIT, _norm, metrics, port_returns
from src.portfolio.sleeves import all_sleeve_equities
from scripts.analysis.regime_lab import load_features
from scripts.analysis.explore_lab import atr
FEE=0.001; LEV=3; POS=0.15

def fr01_daily_equity(asset):
    df=load_features(asset,"1h")
    c=df['close'].values; h=df['high'].values; l=df['low'].values; a=atr(df,14)
    ma=pd.Series(c).rolling(50).mean().values; sd=pd.Series(c).rolling(50).std().values
    ts=pd.to_datetime(df['timestamp'],unit='ms',utc=True)
    eq=np.full(len(c),INIT,float); cap=INIT; last=-1
    for i in range(64,len(c)-1):
        if i<=last or np.isnan(sd[i]) or sd[i]==0 or np.isnan(a[i]): continue
        if df['hurst'].iloc[i]>=0.55: continue
        if np.isnan(df['dvol_pct'].iloc[i]) or df['dvol_pct'].iloc[i]>=0.40: continue
        if c[i]<ma[i]-2.5*sd[i]: d,sl,tp=1,c[i]-2*a[i],ma[i]
        elif c[i]>ma[i]+2.5*sd[i]: d,sl,tp=-1,c[i]+2*a[i],ma[i]
        else: continue
        j=min(i+24,len(c)-1); exit_p=c[j]
        for t in range(i+1,j+1):
            if d==1:
                if l[t]<=sl: exit_p=sl; j=t; break
                if h[t]>=tp: exit_p=tp; j=t; break
            else:
                if h[t]>=sl: exit_p=sl; j=t; break
                if l[t]<=tp: exit_p=tp; j=t; break
        ret=(exit_p-c[i])/c[i]*d*LEV - FEE*LEV
        cap=max(cap+cap*POS*ret,10.0); eq[j:]=cap; last=j
    s=pd.Series(eq,index=ts).resample("1D").last().reindex(IDX).ffill().bfill()
    return _norm(s)

members=all_sleeve_equities()
print(f"PORT06 sleeve: {len(members)} | finestra {IDX[0].date()}..{IDX[-1].date()} | OOS da idx {SPLIT} ({IDX[SPLIT].date()})")
fr={"FR01_BTC":fr01_daily_equity("BTC"), "FR01_ETH":fr01_daily_equity("ETH")}

base=port_returns(members)                       # equal-weight 17 sleeve (metro combine)
aug =port_returns({**members,**fr})              # + FR01x2 (19 sleeve)

def show(tag, dr):
    f=metrics(dr); o=metrics(dr,lo=SPLIT)
    print(f"  {tag:<22} FULL: Sharpe {f['sharpe']:.2f}  DD {f['dd']:.1f}%  ret {f['ret']:+.0f}%   | OOS: Sharpe {o['sharpe']:.2f}  DD {o['dd']:.1f}%  ret {o['ret']:+.0f}%")

print("\n=== MASTER equal-weight: con/senza FR01 ===")
show("PORT06 (17 sleeve)", base)
show("PORT06 + FR01 (19)", aug)

# correlazione FR01 vs portafoglio MASTER aggregato + standalone
for k,e in fr.items():
    r=e.pct_change().fillna(0.0); corr=np.corrcoef(r, base)[0,1]
    f=metrics(r); o=metrics(r,lo=SPLIT)
    print(f"\n  {k}: corr vs MASTER = {corr:+.3f} | standalone OOS Sharpe {o['sharpe']:.2f} DD {o['dd']:.1f}% ret {o['ret']:+.0f}%")
