"""S/T/X/DR y bosque causal en réplicas semisintéticas IHDP de CFRNet."""
import argparse, hashlib, json, platform, urllib.request
from pathlib import Path
import numpy as np
import sklearn
import econml
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
from econml.dml import CausalForestDML

BASE='https://www.fredjo.com/files/'
FILES={
 'ihdp_npci_1-100.train.npz':'750697c71b4f8d7a3aafff771b56a4ac4cd83ec649bf69afb04f8a5aee41a240',
 'ihdp_npci_1-100.test.npz':'a70a8acbcc4e8deb677cc9bf9e9dabeb17caaa37cdbb1d7ba06be7ffb929c41c'}

def fetch(folder):
    folder=Path(folder);folder.mkdir(parents=True,exist_ok=True)
    for name,digest in FILES.items():
        path=folder/name
        if not path.exists():
            with urllib.request.urlopen(BASE+name,timeout=90) as r:data=r.read()
            if hashlib.sha256(data).hexdigest()!=digest:raise ValueError('Hash no coincide')
            path.write_bytes(data)
        if hashlib.sha256(path.read_bytes()).hexdigest()!=digest:raise ValueError('Archivo modificado')
    return [np.load(folder/name) for name in FILES]

def forest(seed): return RandomForestRegressor(n_estimators=80,min_samples_leaf=5,max_features=.8,n_jobs=1,random_state=seed)
def propensity(seed):return RandomForestClassifier(n_estimators=80,min_samples_leaf=5,max_features=.8,n_jobs=1,random_state=seed)

def learners(x,t,y,xt,seed=201):
    t=np.asarray(t,int);ix0=t==0;ix1=t==1
    if min(ix0.sum(),ix1.sum())<4: raise ValueError('Se necesitan al menos cuatro unidades de cada grupo')
    # S: modelo común con tratamiento como covariable; T: dos modelos por grupo.
    s=forest(seed).fit(np.column_stack([x,t]),y)
    s_effect=s.predict(np.column_stack([xt,np.ones(len(xt))]))-s.predict(np.column_stack([xt,np.zeros(len(xt))]))
    m0=forest(seed).fit(x[ix0],y[ix0]);m1=forest(seed+1).fit(x[ix1],y[ix1])
    t_effect=m1.predict(xt)-m0.predict(xt)
    # X: imputa efectos en cada grupo, ajusta modelos y mezcla con propensity.
    d0=m1.predict(x[ix0])-y[ix0];d1=y[ix1]-m0.predict(x[ix1])
    tau0=forest(seed+2).fit(x[ix0],d0);tau1=forest(seed+3).fit(x[ix1],d1)
    e=propensity(seed).fit(x,t).predict_proba(xt)[:,1]
    x_effect=e*tau0.predict(xt)+(1-e)*tau1.predict(xt)
    # DR: pseudoresultado AIPW fuera de pliegue, regresión final sobre X.
    mu0=np.empty(len(y));mu1=np.empty(len(y));p=np.empty(len(y))
    for train,test in StratifiedKFold(2,shuffle=True,random_state=seed).split(x,t):
        mu0[test]=forest(seed).fit(x[train][t[train]==0],y[train][t[train]==0]).predict(x[test])
        mu1[test]=forest(seed+1).fit(x[train][t[train]==1],y[train][t[train]==1]).predict(x[test])
        p[test]=propensity(seed).fit(x[train],t[train]).predict_proba(x[test])[:,1]
    p=np.clip(p,.02,.98)
    pseudo=mu1-mu0+t*(y-mu1)/p-(1-t)*(y-mu0)/(1-p)
    dr=forest(seed+4).fit(x,pseudo).predict(xt)
    cf=CausalForestDML(model_y=forest(seed),model_t=propensity(seed),discrete_treatment=True,
        n_estimators=80,min_samples_leaf=5,max_samples=.45,cv=2,random_state=seed,n_jobs=1)
    cf.fit(y,t,X=x)
    return {'S':s_effect,'T':t_effect,'X':x_effect,'DR':dr,'CausalForest':cf.effect(xt)}

def run(folder,reps=20):
    train,test=fetch(folder)
    if not 1<=reps<=100:raise ValueError('De 1 a 100 réplicas')
    rows=[]
    for i in range(reps):
        x=train['x'][:,:,i];t=train['t'][:,i].astype(int);y=train['yf'][:,i]
        xt=test['x'][:,:,i];truth=test['mu1'][:,i]-test['mu0'][:,i]
        predictions=learners(x,t,y,xt,201)
        rows.append({name:float(np.sqrt(np.mean((pred-truth)**2))) for name,pred in predictions.items()})
        print('réplica',i+1,rows[-1],flush=True)
    summary={name:{'mean':float(np.mean([r[name] for r in rows])),
                   'sd':float(np.std([r[name] for r in rows],ddof=1)) if reps>1 else None} for name in rows[0]}
    return {'reps':reps,'seed':201,'train_n':672,'test_n':75,'hashes':FILES,
            'versions':{'python':platform.python_version(),'numpy':np.__version__,'sklearn':sklearn.__version__,'econml':econml.__version__},
            'metric':'raíz del error cuadrático medio de CATE sobre 75 unidades de test','rows':rows,'summary':summary}

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--data',default='ihdp_data');p.add_argument('--out',default='ihdp_results.json');p.add_argument('--reps',type=int,default=20)
    args=p.parse_args();result=run(args.data,args.reps)
    with Path(args.out).open('x',encoding='utf8') as f:json.dump(result,f,indent=2)
    print('PEHE:',result['summary'])
