"""DiD equilibrado por cohortes; comparaciones y bootstrap por unidad."""
import numpy as np
import pandas as pd

def panel(seed=501,n_early=80,n_late=80,n_never=10,slope=4.):
    rng=np.random.default_rng(seed);cohorts=np.r_[np.full(n_early,2),np.full(n_late,6),np.zeros(n_never,dtype=int)]
    units=np.arange(len(cohorts));times=np.arange(8);intercepts=rng.normal(0,1,len(units))
    out=[]
    for i,g in enumerate(cohorts):
        for t in times:
            treated=int(g>0 and t>=g)
            effect=treated*(1+slope*(t-g) if g==2 else 1.)
            y0=intercepts[i]+.15*t+rng.normal(0,.5)
            out.append((i,t,g,treated,y0+effect,float(effect)))
    return pd.DataFrame(out,columns=['id','time','cohort','treated','y','effect'])

def within(panel,column):
    return (panel[column]-panel.groupby('id')[column].transform('mean')
            -panel.groupby('time')[column].transform('mean')+panel[column].mean()).to_numpy()

def twfe(panel):
    d=within(panel,'treated');y=within(panel,'y');den=d@d
    if den<=1e-12:raise ValueError('Sin variación residual del tratamiento')
    estimate=float(d@y/den);resid=y-estimate*d
    cluster=pd.Series(d*resid).groupby(panel.id.to_numpy()).sum().to_numpy()
    se=float(np.sqrt(cluster@cluster)/den)
    treated=panel.treated.to_numpy()==1
    weights=pd.DataFrame({'cohort':panel.cohort,'time':panel.time,'w':np.where(treated,d/den,0.)})
    effects=weights.groupby(['cohort','time'],as_index=False).w.sum()
    return estimate,se,effects[effects.cohort>0]

def bacon(panel):
    """Descomposición no controlada para panel balanceado y adopción irreversible."""
    cohorts=sorted(g for g in panel.cohort.unique() if g>0);has_never=(panel.cohort==0).any()
    rows=[]
    def add(g1,g2,times,kind):
        sub=panel[panel.cohort.isin([g1,g2]) & panel.time.isin(times)].copy().reset_index(drop=True)
        d=within(sub,'treated');y=within(sub,'y');variance=float(np.mean(d*d))
        if variance<=0:return
        rows.append({'treated_cohort':int(g1),'control_cohort':int(g2),'type':kind,
                     'estimate':float(d@y/(d@d)),'raw_weight':float(len(sub)**2*variance)})
    times=sorted(panel.time.unique())
    if has_never:
        for g in cohorts:add(g,0,times,'tratado vs nunca')
    for i,g in enumerate(cohorts):
        for h in cohorts[i+1:]:
            add(g,h,[t for t in times if t<h],'temprano vs tardío aún no tratado')
            add(h,g,[t for t in times if t>=g],'tardío vs temprano ya tratado')
    total=sum(r['raw_weight'] for r in rows)
    for row in rows:row['weight']=row.pop('raw_weight')/total
    return rows

def att_gt(panel,cohort,time):
    """Diferencia de cambios con base g−1 y controles no tratados en ambos periodos."""
    base=cohort-1
    if time==base:raise ValueError('El periodo base no tiene efecto estimado')
    valid=(panel.cohort==0)|(panel.cohort>max(base,time))
    ids=panel.loc[valid & (panel.cohort!=cohort),'id'].unique()
    treated=panel.loc[panel.cohort==cohort,'id'].unique()
    if not len(ids) or not len(treated):raise ValueError('No hay grupo o controles válidos')
    w=panel[panel.time.isin([base,time])].pivot(index='id',columns='time',values='y')
    change=w[time]-w[base]
    return float(change.loc[treated].mean()-change.loc[ids].mean())

def aggregates(panel):
    cohorts=sorted(g for g in panel.cohort.unique() if g>0);times=sorted(panel.time.unique())
    count=panel.groupby('cohort').id.nunique();cells=[]
    for g in cohorts:
        for t in times:
            if t==g-1:continue
            try:estimate=att_gt(panel,g,t)
            except ValueError:continue
            cells.append({'cohort':int(g),'time':int(t),'event':int(t-g),'n':int(count[g]),'att':estimate})
    event={}
    for e in sorted(set(c['event'] for c in cells)):
        subset=[c for c in cells if c['event']==e]
        event[e]=float(np.average([c['att'] for c in subset],weights=[c['n'] for c in subset]))
    treated=[c for c in cells if c['event']>=0]
    overall=float(np.average([c['att'] for c in treated],weights=[c['n'] for c in treated]))
    return cells,event,overall

def bootstrap(panel,reps=199,seed=501):
    rng=np.random.default_rng(seed);cohorts=panel.groupby('cohort').id.unique().to_dict()
    cells,event,overall=aggregates(panel);events=list(event);draws=[];avgs=[]
    byid={int(i):group for i,group in panel.groupby('id')}
    for _ in range(reps):
        sample=[];newid=0
        for ids in cohorts.values():
            for i in rng.choice(ids,size=len(ids),replace=True):
                piece=byid[int(i)].copy();piece['id']=newid;sample.append(piece);newid+=1
        sample=pd.concat(sample,ignore_index=True)
        _,ev,avg=aggregates(sample);draws.append([ev[e] for e in events]);avgs.append(avg)
    matrix=np.asarray(draws);centres=np.array([event[e] for e in events]);se=matrix.std(axis=0,ddof=1)
    valid=se>0;maxstat=np.max(np.abs((matrix[:,valid]-centres[valid])/se[valid]),axis=1)
    critical=float(np.quantile(maxstat,.95));result=[]
    for i,e in enumerate(events):result.append({'event':int(e),'estimate':event[e],'se':float(se[i]),
       'lower':float(event[e]-critical*se[i]),'upper':float(event[e]+critical*se[i])})
    return {'cells':cells,'event':result,'overall':overall,
            'overall_ci':[float(x) for x in np.quantile(avgs,[.025,.975])],
            'critical':critical,'bootstrap_reps':reps,'bootstrap_seed':seed}
