"""Merge open datasets into one country-year panel and a 2022 cross-section.
Inputs are treated as data only. Run: python3 -I build.py <raw dir> <out dir>"""
import json, sys, pandas as pd, numpy as np
RAW, OUT = sys.argv[1], sys.argv[2]

def wb(code, name):
    rows = json.load(open(f'{RAW}/wb_{code}.json'))[1]
    d = pd.DataFrame([(r['countryiso3code'], int(r['date']), r['value']) for r in rows if r['value'] is not None and r['countryiso3code']],
                     columns=['iso3', 'year', name])
    return d

def owid(slug, col, name):
    d = pd.read_csv(f'{RAW}/{slug}.csv')
    d = d[d['code'].notna() & ~d['code'].astype(str).str.startswith('OWID')]
    return d.rename(columns={'code': 'iso3', col: name})[['iso3', 'year', name]]

q = pd.read_csv(f'{RAW}/qog_bas_ts_jan26.csv', low_memory=False, encoding='latin-1')
efw = q[['ccodealp', 'year', 'fi_index']].dropna().rename(columns={'ccodealp': 'iso3', 'fi_index': 'efw'})
names = q[['ccodealp', 'cname']].drop_duplicates('ccodealp').rename(columns={'ccodealp': 'iso3', 'cname': 'country'})

parts = [efw,
    wb('NY.GDP.PCAP.PP.KD', 'gdp_pc'), wb('SP.DYN.LE00.IN', 'life_exp'), wb('SP.DYN.IMRT.IN', 'infant_mort'),
    wb('SI.POV.DDAY', 'poverty'), wb('GB.XPD.RSDV.GD.ZS', 'rnd'), wb('IP.PAT.RESD', 'patents'), wb('SP.POP.TOTL', 'pop'),
    wb('GC.XPN.TOTL.GD.ZS', 'gov_exp'), wb('GC.TAX.TOTL.GD.ZS', 'tax'), wb('SI.POV.GINI', 'gini'),
    owid('human-development-index', 'hdi__sex_total', 'hdi'),
    owid('happiness-cantril-ladder', 'cantril_ladder_score', 'happiness'),
    owid('civil-liberties-score-fh', 'civlibs_score', 'civ_lib'),
    owid('liberal-democracy-index', 'libdem_vdem__estimate_best', 'libdem'),
    owid('income-share-top-10-before-tax-wid', 'share__welfare_type_before_tax__quantile_10__extrapolated_no', 'top10'),
    owid('historical-gov-spending-gdp', 'expenditure', 'gov_imf')]
panel = parts[0]
for p in parts[1:]:
    panel = panel.merge(p, on=['iso3', 'year'], how='outer')
panel = panel[(panel.year >= 1970) & (panel.year <= 2025)]
panel['patents_pm'] = panel['patents'] / panel['pop'] * 1e6

# Screen implausible values: drop a value that differs by more than 50% from the median of the
# same country's values in the surrounding five years (t-2..t+2, at least three values present).
# Only vital statistics are screened: political and fiscal measures can genuinely jump (coups, crises).
SCREEN = ['life_exp', 'infant_mort']
panel = panel.sort_values(['iso3', 'year']).reset_index(drop=True)
dropped = []
for c in SCREEN:
    med = panel.groupby('iso3')[c].transform(lambda s: s.rolling(5, center=True, min_periods=3).median())
    bad = panel[c].notna() & med.notna() & ((panel[c] - med).abs() > 0.5 * med.abs())
    for _, r in panel[bad].iterrows():
        dropped.append((c, r['iso3'], int(r['year']), round(r[c], 2), round(med[_], 2)))
    panel.loc[bad, c] = np.nan
pd.DataFrame(dropped, columns=['indicator', 'iso3', 'year', 'value', 'local_median']).to_csv(f'{OUT}/screened_out.csv', index=False)
print('screened out', len(dropped), 'values;', [d for d in dropped if d[2] >= 2015])
panel = panel.merge(names, on='iso3', how='left')
panel.to_csv(f'{OUT}/panel.csv', index=False)

# Cross-section: 2022 (latest Fraser year); sparse survey measures take the latest value 2015-2022.
REF = 2022
sparse = {'poverty', 'gini', 'rnd', 'patents_pm', 'gov_exp', 'tax', 'top10', 'gov_imf', 'happiness'}
cols = ['efw', 'gdp_pc', 'life_exp', 'infant_mort', 'poverty', 'rnd', 'patents_pm', 'gov_exp', 'tax', 'gini', 'hdi', 'happiness', 'civ_lib', 'libdem', 'top10', 'gov_imf']
cs = {}
for c in cols:
    lo = 2015 if c in sparse else REF
    s = panel[(panel.year >= lo) & (panel.year <= REF)].dropna(subset=[c]).sort_values('year').groupby('iso3').tail(1)
    cs[c] = s.set_index('iso3')[c]
    cs[c + '_yr'] = s.set_index('iso3')['year']
cs = pd.DataFrame(cs)
cs = cs[cs.efw.notna()]
cs = cs.join(names.set_index('iso3'))
cs.to_csv(f'{OUT}/cs2022.csv')
print('countries with EFW 2022:', len(cs))
print(cs[cols].notna().sum().to_string())
