"""Validate cross-table identities; optional append-only comparison with next edition."""
from pathlib import Path
import pandas as pd, numpy as np, json, argparse
p=argparse.ArgumentParser();p.add_argument('--data',default='data');p.add_argument('--next');a=p.parse_args();root=Path(a.data);t={f.stem:pd.read_csv(f,keep_default_na=False) for f in root.glob('*.csv')};checks=[]
def check(name,result):
 assert bool(result),name
 checks.append(name)
def eq(x,y):return np.allclose(x,y,rtol=0,atol=.02)
def flow(df,key,op,cl):
 return eq(df[op].to_numpy()[1:],df[cl].to_numpy()[:-1]) if key is None else eq(df.groupby(key)[cl].shift().fillna(0),df[op])
d=t['deliveries'];w=t['wishlists'];pr=t['production'];m=t['materials'];g=t['magic'];h=t['households'];e=t['economy'];r=t['ukraine_regions'];an=t['annual_summary'];s=t['country_spirit'];wf=t['workforce'];re=t['reindeer'];
keys={'recipes':['category','material'],'magic_recipes':['category'],'destinations':['code'],'events':['year'],'wishlists':['year','month','code','category'],'country_spirit':['year','month','code'],'production':['date','category'],'materials':['date','material'],'magic':['date'],'workforce':['date','department'],'households':['year','month'],'economy':['year','month'],'deliveries':['year','code','category'],'ukraine_regions':['year','region'],'reindeer':['year'],'annual_summary':['year']}
for k,cols in keys.items():check('unique key '+k,not t[k].duplicated(cols).any());check('no nulls '+k,not t[k].isna().any().any())
for k in ['deliveries','wishlists','country_spirit']:check('destination scope '+k,set(t[k].code)==set(t['destinations'].code) and 'RU' not in set(t[k].code))
check('production inventory',eq(pr.opening_inventory+pr.accepted-pr.shipped,pr.closing_inventory));check('production rejects',eq(pr.gross-pr.rejects,pr.accepted));check('production continuity',flow(pr,'category','opening_inventory','closing_inventory'));check('materials balance',eq(m.opening_milliunits+m.receipts_milliunits-m.consumed_milliunits,m.closing_milliunits));check('materials continuity',flow(m,'material','opening_milliunits','closing_milliunits'));check('magic balance',eq(g.opening_jg+g.generated_jg-g.curtailed_jg-g.leakage_jg-g.factory_jg-g.sleigh_jg,g.closing_jg));check('magic continuity',flow(g,None,'opening_jg','closing_jg'));check('nonnegative reserves',(g.closing_jg>=0).all() and (m.closing_milliunits>=0).all() and (pr.closing_inventory>=0).all());check('wish totals',eq(w.baseline_requests+w.hope_requests,w.total_requests));check('delivery totals',eq(d.baseline_requested+d.hope_requested-d.baseline_delivered-d.hope_delivered,d.unfilled));check('no overdelivery',(d.baseline_delivered<=d.baseline_requested).all() and (d.hope_delivered<=d.hope_requested).all());check('Hope policy',((d.hope_requested>0)==((d.year>=2023)&(d.code=='UA')&(d.baseline_requested>0))).all());
keys2=['year','code','category'];check('wishlists reconcile with orders',eq(w.groupby(keys2)[['baseline_requests','hope_requests']].sum().sort_index(),d.set_index(keys2)[['baseline_requested','hope_requested']].sort_index()));check('Ukraine region totals',eq(r.groupby('year')[['baseline_requested','hope_requested','baseline_delivered','hope_delivered']].sum(),d[d.code=='UA'].groupby('year')[['baseline_requested','hope_requested','baseline_delivered','hope_delivered']].sum()));check('Ukraine all regions',r.groupby('year').region.nunique().eq(27).all());check('annual dispatch',eq(pr.assign(year=pr.date.str[:4].astype(int)).groupby('year').shipped.sum(),d.groupby('year')[['baseline_delivered','hope_delivered']].sum().sum(axis=1)));check('magic trade',eq(g.assign(year=g.date.str[:4].astype(int),month=g.date.str[5:7].astype(int)).groupby(['year','month']).generated_jg.sum(),s.groupby(['year','month']).magic_generated_jg.sum()));check('household savings',eq(h.opening_savings_snf+h.wages_snf-h.consumption_snf,h.closing_savings_snf));check('household continuity',flow(h,None,'opening_savings_snf','closing_savings_snf'));check('employment',eq(h.employed+h.unemployed,h.labor_force));check('GDP identity',eq(e.toy_output_snf-e.intermediate_inputs_snf,e.toy_value_added_snf) and eq(e.toy_value_added_snf+e.services_value_added_snf,e.gdp_snf));check('annual GDP',eq(e.groupby('year').gdp_snf.sum(),an.gdp_snf));check('reindeer capacity',(re.payload_toys<=re.capacity_toys).all());check('reindeer magic',eq(re.magic_jg,g.assign(year=g.date.str[:4].astype(int)).groupby('year').sleigh_jg.sum()));check('annual deliveries',eq(re.payload_toys,an.delivered));check('daily magic recipe',eq(pr.pivot(index='date',columns='category',values='gross') @ t['magic_recipes'].set_index('category').jg_per_gross_toy,g.set_index('date').factory_jg));recipe=t['recipes'].pivot(index='category',columns='material',values='milliunits_per_toy'); expected=pr.pivot(index='date',columns='category',values='gross')@recipe; actual=m.pivot(index='date',columns='material',values='consumed_milliunits');check('material recipes',eq(expected.drop(columns='hot_chocolate'),actual.drop(columns='hot_chocolate')));check('cocoa workforce',eq(wf.groupby('date').cocoa_milli_liters.sum(),actual.hot_chocolate));check('wages household',eq(wf.assign(year=wf.date.str[:4].astype(int),month=wf.date.str[5:7].astype(int)).groupby(['year','month']).wages_snf.sum(),h.wages_snf));
check('finite magic storage', (g.closing_jg<=g.capacity_jg).all() and (g.curtailed_jg>=0).all());check('storage cost positive', (e.inventory_storage_cost_snf>=0).all() and (e.inventory_storage_cost_snf<=e.intermediate_inputs_snf).all());check('daily factory below plan',(pr.gross<=pr.planned).all());check('no delivery outside Christmas Eve',(pr.loc[~pr.date.str.endswith('12-24'),'shipped']==0).all());check('region allocations bounded',(r.baseline_delivered<=r.baseline_requested).all() and (r.hope_delivered<=r.hope_requested).all());
# --- Edition 2025.3 audit additions (issue #639): coverage, ranges, annual stocks, labour, prices, logistics. Original checks above are unchanged.
def rel(x,y,r=1e-6,at=1.0):return bool((np.abs(np.asarray(x,float)-np.asarray(y,float))<=at+r*np.abs(np.asarray(y,float))).all())
yr=lambda df:df.date.str[:4].astype(int);mon=lambda df:df.date.str[5:7].astype(int);cpi=e.set_index(['year','month']).cpi;ym=lambda df:pd.MultiIndex.from_arrays([yr(df),mon(df)])
check('finite numeric values',all(np.isfinite(v.select_dtypes('number').to_numpy(float)).all() for v in t.values()))
check('nonnegative quantities',all((v.select_dtypes('number').drop(columns=['toy_value_added_snf'],errors='ignore')>=0).all().all() for v in t.values()) and (t['destinations'].synthetic_weight>0).all())
check('index ranges',s.spirit_index.between(0,100).all() and s.belief_index.between(0,100).all() and wf.happiness_index.between(0,100).all() and h.happiness_index.between(0,100).all() and (g.aurora_index>0).all())
cal=pd.date_range(f'{an.year.min()}-01-01',f'{an.year.max()}-12-31').strftime('%Y-%m-%d')
check('complete daily calendar',list(g.date)==list(cal) and all(len(t[k])==len(cal)*n and set(t[k].date)==set(cal) for k,n in [('production',25),('materials',20),('workforce',5)]))
check('complete monthly and annual coverage',all(set(zip(t[k].year,t[k].month))==set(zip(yr(g),mon(g))) for k in ('households','economy')) and all(list(t[k].year)==list(an.year) for k in ('reindeer','events')))
check('complete destination grids',all(t[k].groupby([c for c in ('year','month') if c in t[k]]).code.nunique().eq(len(t['destinations'])).all() for k in ('wishlists','country_spirit','deliveries')))
check('category and material keys',set(pr.category)==set(t['magic_recipes'].category)==set(t['recipes'].category)==set(d.category)==set(w.category) and set(m.material)==set(t['recipes'].material) and len(t['recipes'])==t['recipes'].category.nunique()*t['recipes'].material.nunique())
REG='Crimea|Sevastopol|Cherkasy|Chernihiv|Chernivtsi|Dnipropetrovsk|Donetsk|Ivano-Frankivsk|Kharkiv|Kherson|Khmelnytskyi|Kirovohrad|Kyiv city|Kyiv oblast|Luhansk|Lviv|Mykolaiv|Odesa|Poltava|Rivne|Sumy|Ternopil|Vinnytsia|Volyn|Zakarpattia|Zaporizhzhia|Zhytomyr'.split('|')
check('Ukraine named regions',all(sorted(x.region)==sorted(REG) for _,x in r.groupby('year')))
A=an.set_index('year');P=pr.assign(year=yr(pr));G=g.assign(year=yr(g))
check('annual demand',eq(A.demand,d.groupby('year')[['baseline_requested','hope_requested']].sum().sum(axis=1)) and eq(A.hope_delivered,d.groupby('year').hope_delivered.sum()))
check('annual production',eq(A[['gross','accepted','rejected']],P.groupby('year')[['gross','accepted','rejects']].sum().set_axis(['gross','accepted','rejected'],axis=1)))
check('annual closing inventory',eq(A.inventory,P[P.date.str.endswith('12-31')].groupby('year').closing_inventory.sum()))
check('annual magic',eq(A.magic_generated,G.groupby('year').generated_jg.sum()) and eq(A.magic_used,G.groupby('year')[['factory_jg','sleigh_jg']].sum().sum(axis=1)) and eq(A.magic_reserves,G[G.date.str.endswith('12-31')].set_index('year').closing_jg))
W=wf.assign(year=yr(wf),month=mon(wf));hd=W.groupby(['year','month','date']).employed.sum()
check('workforce headcount',(hd.groupby(['year','month']).min()==h.set_index(['year','month']).employed).all() and (hd.groupby(['year','month']).max()==h.set_index(['year','month']).employed).all())
hr=(wf.paid_hours/wf.employed.where(wf.employed>0)).groupby(wf.date)
check('uniform daily paid hours',(hr.nunique()<=1).all() and set(hr.first().dropna().unique())<= {4.0,8.0,10.0})
rate=wf.wages_snf/(wf.paid_hours*cpi.reindex(ym(wf)).to_numpy()/100)
check('wage rates constant in real terms',(rate.groupby(wf.department).agg(lambda x:x.max()/x.min()-1)<1e-5).all())
check('household morale',eq(h.happiness_index,W[W.department==W.department.iloc[0]].groupby(['year','month']).happiness_index.mean().round(3).to_numpy()))
check('toy output valuation',rel(e.set_index(['year','month']).toy_output_snf,P.assign(month=mon(pr)).groupby(['year','month']).accepted.sum()*4*cpi/100))
st=(P.assign(month=mon(pr)).groupby(['year','month','date']).opening_inventory.sum()*.2).groupby(['year','month']).sum()*cpi/100/365.25
check('storage cost from inventory',rel(e.set_index(['year','month']).inventory_storage_cost_snf,st))
mc=(m.consumed_milliunits*m.price_snf_per_unit/1000).groupby(ym(m)).sum()
check('intermediate inputs from materials',rel(e.set_index(['year','month']).intermediate_inputs_snf,mc+e.set_index(['year','month']).inventory_storage_cost_snf))
check('services from consumption',eq(e.services_value_added_snf,(h.consumption_snf*.6).round(2)))
x24=pr[pr.date.str.endswith('12-24')].groupby('date').shipped.sum()
check('sleigh magic per shipment',(g.set_index('date').loc[x24.index].sleigh_jg==(x24+2)//3).all() and (g.loc[~g.date.str.endswith('12-24'),'sleigh_jg']==0).all())
check('annual storage capacity',G.groupby('year').capacity_jg.nunique().eq(1).all())
check('reindeer derived metrics',eq(re.flight_hours,(re.payload_toys/20000).round(3)) and eq(re.equivalent_distance_km,(re.payload_toys*.045).round(2)) and eq(re.carrots_kg,(re.payload_toys*.00018).round(3)))
um=d[(d.code=='UA')&(d.hope_delivered<d.hope_requested)][['year','category']]
check('Hope dispatch priority',d.merge(um,on=['year','category']).baseline_delivered.sum()==0)
if a.next:
 check('next edition table set',sorted(f.name for f in Path(a.next).glob('*.csv'))==sorted(f.name for f in root.glob('*.csv')))
 for f in root.glob('*.csv'):
  with f.open('rb') as first,(Path(a.next)/f.name).open('rb') as nxt:
   check('append-only byte prefix '+f.name,nxt.read(f.stat().st_size)==first.read())
if a.next:
 for f in root.glob('*.csv'):
  o=t[f.stem];n=pd.read_csv(Path(a.next)/f.name,keep_default_na=False);new=n.iloc[len(o):]
  check('appended rows are later years '+f.name,len(new)==0 or (('year' in n and (new.year>o.year.max()).all()) or ('date' in n and (new.date.str[:4].astype(int)>int(o.date.str[:4].max())).all())))
print(json.dumps({'status':'PASS','checks':checks,'counts':{k:len(v) for k,v in t.items()},'rows':sum(map(len,t.values()))},indent=2))
