#!/usr/bin/env python3
"""Refresh Brailio's African country list and disability-data extract from official open APIs."""
import csv, json, urllib.request, datetime
import subprocess, sys
from pathlib import Path
OUT=Path(__file__).resolve().parents[1]/"data"; OUT.mkdir(exist_ok=True)
UA="Brailio/1.0 (https://ud-congo.com/)"
AFRICA={"DZA","AGO","BEN","BWA","BFA","BDI","CPV","CMR","CAF","TCD","COM","COG","COD","CIV","DJI","EGY","GNQ","ERI","SWZ","ETH","GAB","GMB","GHA","GIN","GNB","KEN","LSO","LBR","LBY","MDG","MWI","MLI","MRT","MUS","MAR","MOZ","NAM","NER","NGA","RWA","STP","SEN","SYC","SLE","SOM","ZAF","SSD","SDN","TZA","TGO","TUN","UGA","ZMB","ZWE"}
def get(url):
 req=urllib.request.Request(url,headers={"User-Agent":UA,"Accept":"application/json"})
 with urllib.request.urlopen(req,timeout=60) as r:return json.load(r)
def save(name,obj): (OUT/name).write_text(json.dumps(obj,ensure_ascii=False,indent=2),encoding="utf-8")
now=datetime.datetime.now(datetime.timezone.utc).isoformat()
country_url="https://api.worldbank.org/v2/country?format=json&per_page=300"
countries=get(country_url)[1]
countries=[c for c in countries if c.get("id") in AFRICA]
save("worldbank_african_country_codes.json",{"source":"World Bank Countries API","source_url":country_url,"license":"CC BY 4.0, subject to dataset notices","downloaded_utc":now,"countries":countries})
indicator="adj_al_alot_dfcl_all"
url=f"https://api.worldbank.org/v2/country/all/indicator/{indicator}?source=92&format=json&per_page=20000"
resp=get(url); rows=[]
for r in resp[1] or []:
 c=r.get("country",{}); iso=c.get("id")
 if iso not in AFRICA:continue
 rows.append({"country":c.get("value"),"iso3":iso,"year":r.get("date"),"value":r.get("value"),"unit":r.get("unit"),"indicator_id":indicator,"indicator":r.get("indicator",{}).get("value"),"source_id":"92","source":"World Bank Disability Data Hub","source_url":f"https://api.worldbank.org/v2/country/{iso}/indicator/{indicator}?source=92&format=json"})
rows.sort(key=lambda x:(x["iso3"],x["year"]))
save("worldbank_disability_prevalence_africa.json",{"title":"Adjusted prevalence of persons with disabilities","indicator_id":indicator,"definition":"Adjusted prevalence of persons aged 15+ with disabilities, defined as at least a lot of functional difficulty, as a percentage of persons.","source":"World Bank Disability Data Hub (source 92)","source_url":"https://disabilitydata.worldbank.org/en/","api_url":url,"license":"Creative Commons Attribution 4.0 International for the Disability Data catalog; original source and year should accompany every reused observation.","license_url":"https://datacatalog.worldbank.org/public-licenses","downloaded_utc":now,"observations":rows})
with (OUT/"worldbank_disability_prevalence_africa.csv").open("w",encoding="utf-8-sig",newline="") as f:
 w=csv.DictWriter(f,fieldnames=list(rows[0]) if rows else ["country"]);w.writeheader();w.writerows(rows)
latest={}
for row in rows:
 if row["value"] is not None and (row["iso3"] not in latest or int(row["year"])>int(latest[row["iso3"]]["year"])):
  latest[row["iso3"]]=row
values=[]
for country in countries:
 row=latest.get(country["id"])
 values.append({"name":country["name"],"iso3":country["id"],"value":row["value"] if row else None,"year":row["year"] if row else None})
values.sort(key=lambda x:x["name"])
save("africa_latest_disability.json",{"source":"World Bank Disability Data Hub, indicator "+indicator,"downloaded_utc":now,"coverage_note":"Null means no observation is published in this extract; it is not a zero prevalence.","countries_with_values":len(latest),"countries_total":len(values),"values":values})
subprocess.run([sys.executable,str(Path(__file__).with_name("build_pages.py"))],check=True)
print(f"Pays africains: {len(countries)}; observations du Hub: {len(rows)}; pays avec une valeur: {len({r['iso3'] for r in rows if r['value'] is not None})}")
