"""Informe reproducible: factores oficiales y cartera sintética."""
import os,io,zipfile,re
from pathlib import Path
import numpy as np
import pandas as pd
from p01data import FRENCH,fetch,french_monthly,sha256
from p01metrics import report
def experiment():
    root=Path(os.environ.get('P01_FACTOR_ROOT',Path('p01_project')/'raw'))
    factors_path=root/'F-F_Research_Data_Factors_CSV.zip'
    mom_path=Path(os.environ.get('P01_MOM_PATH',root/'french_momentum.zip'))
    factors_raw=fetch(FRENCH,factors_path)
    mom_raw=fetch('https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Momentum_Factor_CSV.zip',mom_path)
    ff=french_monthly(factors_raw).set_index('mes')
    with zipfile.ZipFile(io.BytesIO(mom_raw)) as z: txt=z.read(z.namelist()[0]).decode('latin-1')
    rows=[]
    for line in txt.splitlines():
        if re.match(r'^\s*\d{6}\s*,',line):
            a=line.split(','); rows.append((pd.to_datetime(a[0].strip(),format='%Y%m'),float(a[1])/100))
    mom=pd.Series(dict(rows),name='mom')
    factors=ff.join(mom,how='inner').loc['2010-01-01':'2023-12-01',['mkt_rf','smb','hml','mom']]
    rng=np.random.default_rng(4105)
    y=pd.Series(.002+factors.to_numpy()@np.array([1.1,.3,-.2,.6])+rng.normal(0,.02,len(factors)),index=factors.index,name='retorno_exceso_sintetico')
    out=Path(os.environ.get('P01_REPORT_PATH',Path('p01_project')/'tearsheet.html'))
    result=report(out,y,factors)
    print('Factores SHA256:',sha256(factors_raw),'| momentum SHA256:',sha256(mom_raw))
    print('Meses:',len(y),'| alfa sintético mensual verdadero: 0.002')
    for k,v in result.items(): print(k,':',v)
    print('Informe HTML:',out.resolve())
if __name__=='__main__': experiment()
