"""Offline data reconstruction. Optional rendering uses already installed tools only."""
from pathlib import Path
from decimal import Decimal
import argparse,csv,json,shutil,subprocess,sys
p=argparse.ArgumentParser();p.add_argument('--out',type=Path,required=True);p.add_argument('--render-png',action='store_true');args=p.parse_args()
root=Path(__file__).resolve().parent;out=args.out.resolve()
assert out!=root,'Choose a separate reproduction output directory'
out.mkdir(parents=True,exist_ok=True)
j=json.loads((root/'eurostat-eu27-snapshot.json').read_text())
EU=set('BE BG CZ DK DE EE IE EL ES FR HR IT CY LV LT LU HU MT NL AT PL PT RO SI SK FI SE'.split())
assert set(j['dimension']['geo']['category']['index'])==EU|{'EU27_2020'}
def cell(g,r):
 choices={'freq':'A','unit':'PC','rskpovth':r,'age':'TOTAL','sex':'T','geo':g,'time':'2025'};idx=0
 for d,s in zip(j['id'],j['size']):idx=idx*s+j['dimension'][d]['category']['index'][choices[d]]
 return j['value'].get(str(idx)),j.get('status',{}).get(str(idx),'')
rows=[]
for g in EU|{'EU27_2020'}:
 t,tf=cell(g,'TOTAL');a,af=cell(g,'A_60');b,bf=cell(g,'B_60');assert all(v is not None and 0<=v<=100 for v in [t,a,b])
 gap=float((Decimal(str(b))-Decimal(str(a))).quantize(Decimal('.1')))
 rows.append(dict(geo=g,country=j['dimension']['geo']['category']['label'][g],year=2025,total_pct=t,above_threshold_pct=a,below_threshold_pct=b,gap_pp=gap,total_flag=tf,above_flag=af,below_flag=bf))
rows.sort(key=lambda x:(x['geo']!='EU27_2020',-x['gap_pp'],x['country']))
with (out/'chart-data.csv').open('w',newline='') as f:
 w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
(out/'chart-data.json').write_text(json.dumps(rows,indent=2)+'\n')
if args.render_png:subprocess.run([sys.executable,str(root/'render_chart.py'),'--out',str(out)],check=True)
print(json.dumps({'status':'PASS','rows':len(rows),'sourceCells':84,'networkUsed':False,'rendered':args.render_png}))
