"""Workbook v2: merged canonical panel (Mia + Claude), Census 2012-13 moved to March-2020 vintage."""
import pandas as pd, numpy as np
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils import get_column_letter
from paper_2012_14 import paper
U='/mnt/user-data/uploads/'
m=pd.read_csv(U+'merged_panel.csv'); p=pd.read_csv('out/spending_growth_index_panel.csv')
cf=pd.read_csv(U+'counterfactual_2009d.csv'); f1=pd.read_csv(U+'figure1_shares.csv')
# --- Census: merged levels, with 2012-13 replaced by the March-2020 published Table 1 values
c=m[['state','year','dge','dge_source','dge_raked_2001_2003']].copy(); c['dge']/=1e6; c['dge_raked_2001_2003']/=1e6
fix=p[p.year.isin([2012,2013])].set_index(['state','year']).dge
k=c.year.isin([2012,2013])
c.loc[k,'dge']=[fix[(s,y)] for s,y in zip(c.state[k],c.year[k])]
c.loc[k,'dge_source']='Table1-2020vintage (12/13slsstab1a/b.xlsx)'
c=c.sort_values(['state','year'])
lv=c[c.dge.notna()].copy(); gap=lv.groupby('state').year.diff()
lv['g_dge']=(lv.dge/lv.groupby('state').dge.shift(1))**(1/gap)-1
c=c.merge(lv[['state','year','g_dge']],on=['state','year'],how='left')
c['g_dge']=c.groupby('state').g_dge.bfill(limit=1).where(c.dge.isna(),c.g_dge)   # 2001<-2002, 2003<-2004
# --- BEA side + private growth from Claude's build (identical to Mia's; includes 2025 and SIC-basis 1997 growth)
b=p[p.state!='United States'][['state','year','basis','gdp_private','gdp_sl','g_private','g_sl_bea','idx_bea','idx_bea_3yr','idx_bea_3yr_rank','share_sl','share_sl_window_start','mining_share_start']]
d=b.merge(c,on=['state','year'],how='left').sort_values(['state','year'])
d['idx_census']=d.g_private-d.g_dge
d['idx_census_3yr']=d.groupby('state').idx_census.transform(lambda s:s.rolling(3,min_periods=3).mean())
d['idx_census_3yr_rank']=d.groupby('year').idx_census_3yr.rank(ascending=False,method='min')
d['window']=(d.year-2).astype(str)+'-'+d.year.astype(str)
d.to_csv('out/spending_growth_index_panel_v2.csv',index=False)
# checks
chk=d.merge(m[['state','year','idx_census_3yr']],on=['state','year'],suffixes=('','_mia'))
diff=(chk.idx_census_3yr-chk.idx_census_3yr_mia).abs()
print('windows differing from Mia merged (>1e-9):',sorted(chk[diff>1e-9].year.unique()))
print('windows restored:',sorted(chk[chk.idx_census_3yr.notna()&chk.idx_census_3yr_mia.isna()].year.unique()))
def latest(col,end):
    x=d[d.year==end][['state',col,col+'_rank']].sort_values(col,ascending=False); x.columns=['State',f'Index avg {end-2}-{str(end)[2:]}','Rank']; return x
ctx=d[d.year==2025][['state','share_sl','share_sl_window_start','mining_share_start']]
ctx.columns=['State','S&L share of GDP, 2025','S&L share of GDP, 2022','Mining share of private GDP, 2022']
both=latest('idx_bea_3yr',2025).merge(latest('idx_census_3yr',2024),on='State',suffixes=(' (BEA)',' (Census)')).merge(ctx,on='State')
def wide(col):
    w=d.pivot(index='state',columns='year',values=col).dropna(axis=1,how='all'); w.columns=[f'{y-2}-{str(y)[2:]}' for y in w.columns]
    n=(w<0).sum(axis=1); t=w.notna().sum(axis=1); w['Windows negative']=n; w['Windows total']=t
    return w.reset_index().rename(columns={'state':'State'})
rep=d[d.year==2014].set_index('state')[['idx_census_3yr','idx_bea_3yr']].join(paper,how='inner').reset_index()
rep=rep[['state','paper_census','idx_census_3yr','paper_bea','idx_bea_3yr']]; rep['Census diff']=rep.idx_census_3yr-rep.paper_census; rep['BEA diff']=rep.idx_bea_3yr-rep.paper_bea
rep.columns=['State','Paper: Census 2012-14','Rebuilt: Census 2012-14','Paper: BEA 2012-14','Rebuilt: BEA 2012-14','Census diff','BEA diff']
print('replication corr census %.3f bea %.3f'%(rep.iloc[:,1].corr(rep.iloc[:,2]),rep.iloc[:,3].corr(rep.iloc[:,4])))
cfo=cf.copy(); cfo.columns=['Year','US S&L share','Actual S&L value added ($M, 2009 dollars)','Counterfactual at 1963 share ($M, 2009 dollars)','Excess over counterfactual ($M, 2009 dollars)','Excess as share of S&L + private GSP']
cfo.insert(1,'Basis',np.where(cfo.Year<1997,'SIC','NAICS'))
f1['col']=f1.year.astype(str)+np.where((f1.year==1997),' '+f1.classification,'')
order=f1.drop_duplicates('col').sort_values(['year','classification'],ascending=[True,False]).col.tolist()
fw=f1.pivot(index='state',columns='col',values='slg_share')[order].reset_index().rename(columns={'state':'State or BEA region'})
regions=['New England','Mideast','Great Lakes','Plains','Southeast','Southwest','Rocky Mountain','Far West']
fw['_r']=fw['State or BEA region'].isin(regions); fw=fw.sort_values(['_r','State or BEA region'],ascending=[False,True]).drop(columns='_r')
notes=[
['Spending Growth Index: Millsap & Ishmael (2017), extended 1963-2025. Merged build, version 2'],
['Built 5 Oct 2026. Merges two independent rebuilds (Mia\'s and Claude\'s). The BEA sides were identical; the Census series is Mia\'s merged panel with one further correction described below. Mia\'s scripts and MERGE_NOTES.md are the reproducibility layer.'],
[''],
['DEFINITIONS'],
['Index = annual growth of private-industry GSP minus annual growth of the government measure, averaged over three years. Positive = private sector grew faster. Same definition as the paper.'],
['BEA version: government measure is state and local government value added (SAGDP2 line 86; SIC table line 75).'],
['Census version: government measure is state and local direct general expenditure (Census aggregate line 66), fiscal years, paired with calendar-year GSP as in the paper.'],
['All growth rates are nominal. Nominal reproduces the paper\'s 2012-14 tables better than chained-dollar growth.'],
['S&L share = S&L value added / (S&L value added + private-industry GSP), the paper\'s Figure 1 ratio.'],
[''],
['COVERAGE'],
['BEA index: annual 1964-2025; three-year windows 1964-66 through 2023-25.'],
['Census index: annual 1964-2024; three-year windows 1964-66 through 2022-24.'],
[''],
['CENSUS SOURCES BY YEAR'],
['1963-1997: Census historical database (Govt_Finances.mdb).'],
['1998-2011 and 2016-2024: public-use state-by-type files, aggregated with Census\'s line-66 item-code list (Mia\'s extract).'],
['2012-2015: published Table 1, March 2020 revision.'],
['2001 and 2003: no state-area survey. Growth is the annualised two-year rate, assigned to both years. Mia\'s raked levels are kept in the panel column dge_raked_2001_2003 as a sensitivity check and are not used in the index.'],
[''],
['CHANGES FROM MIA\'S merged_panel.csv'],
['2012-2013 levels: the merged panel still carried pre-2020 public-use values for these two years, which left a false jump into 2014 (Oregon +19%, Alabama +10%). They are replaced here with the March 2020 Table 1 values, the same vintage already adopted for 2014-15. This changes Census windows ending 2012 through 2016.'],
['1997-1999 windows: restored. The merged panel left them blank; 1997 growth is computed here on the SIC basis and 1998 growth on the NAICS basis, so no growth rate spans the break.'],
['BEA index and the 2023-25 window come from Claude\'s build (the merged panel stops at 2024).'],
[''],
['CAVEATS'],
['1997 SIC-to-NAICS break: share levels are not comparable across it (US 1997: 8.9% SIC, 9.2% NAICS). The counterfactual holds the 1963 SIC-basis share constant across the break, so part of the post-1997 excess reflects reclassification.'],
['Small unreconciled differences remain between the public-use extract and the historical database or published tables in 2007-08 (up to 3%, e.g. Nebraska and Louisiana) and 2017 (up to 1%).'],
['New Jersey: public-use values run about 6% above the published 2017-19 tables, so its 2017 Census growth is partly a revision effect.'],
['2022: July 2026 public-use levels are 1.4% above the published 2022 table nationally. Treat 2022 Census growth with caution.'],
['Florida: BEA shows S&L value added falling 5.4% in 2023, which lifts its 2023-25 BEA rank. DC\'s S&L base is about 3% of its economy, so its BEA score is noisy.'],
['Current data include BEA\'s 2018 and 2023 comprehensive revisions, so 2012-14 values differ from the paper (see Replication sheet).'],
['The index measures a growth differential. It moves with private-sector volatility, commodity states especially, and says nothing about spending levels.'],
['BEA 2025 state GDP is the first annual estimate and will be revised.'],
]
out='out/spending_growth_index_1963_2025_v2.xlsx'
with pd.ExcelWriter(out,engine='openpyxl') as xw:
    pd.DataFrame(notes).to_excel(xw,sheet_name='Read me',index=False,header=False)
    both.to_excel(xw,sheet_name='Latest rankings',index=False)
    rep.to_excel(xw,sheet_name='Replication 2012-14',index=False)
    wide('idx_bea_3yr').to_excel(xw,sheet_name='BEA index 3yr',index=False)
    wide('idx_census_3yr').to_excel(xw,sheet_name='Census index 3yr',index=False)
    cfo.to_excel(xw,sheet_name='Counterfactual',index=False)
    fw.to_excel(xw,sheet_name='Figure 1 shares',index=False)
    d.to_excel(xw,sheet_name='Panel',index=False)
wb=load_workbook(out); red=Font(name='Arial',size=10,color='C00000',bold=True)
heads=[i+1 for i,r in enumerate(notes) if r[0] and r[0].isupper()]
for ws in wb:
    for row in ws.iter_rows():
        for c_ in row: c_.font=Font(name='Arial',size=10,bold=(c_.row==1 and ws.title!='Read me'))
    if ws.title=='Read me':
        ws.column_dimensions['A'].width=150
        for r in [1]+heads: ws.cell(r,1).font=Font(name='Arial',size=11,bold=True)
        for row in ws.iter_rows(): row[0].alignment=Alignment(wrap_text=True,vertical='top')
        continue
    ws.freeze_panes='B2'; ws.row_dimensions[1].height=58
    for i,c_ in enumerate(ws[1],1):
        c_.alignment=Alignment(wrap_text=True,vertical='bottom'); c_.fill=PatternFill('solid',fgColor='E7E6E6')
        ws.column_dimensions[get_column_letter(i)].width=22 if i==1 else 13
        h=str(c_.value); fmt=None
        if ws.title=='Figure 1 shares' and i>1: fmt='0.0%'
        elif 'share' in h.lower(): fmt='0.0%'
        elif h.startswith(('Index','Paper','Rebuilt','idx','g_')) or 'diff' in h or (len(h)==7 and h[4]=='-'): fmt='0.000'
        elif '$M' in h or (h.startswith(('gdp','dge')) and h!='dge_source'): fmt='#,##0'
        if fmt:
            for r in range(2,ws.max_row+1):
                cell=ws.cell(r,i); cell.number_format=fmt
                if fmt=='0.000' and isinstance(cell.value,(int,float)) and cell.value<0 and ws.title!='Panel': cell.font=red
wb.save(out)
x=pd.read_excel(out,sheet_name=None); print({k_:v.shape for k_,v in x.items()})
print(both.iloc[:,:5].round(3).head(6).to_string()); print(both[both.State=='Missouri'].round(3).to_string())
w=x['Census index 3yr'].set_index('State'); print(w.loc[['Oregon','Alabama','Missouri'],['2010-12','2011-13','2012-14','2013-15','2014-16']].round(3))
print('blank cols census:',[c for c in w.columns if w[c].isna().all()])
