"""Download the raw source files listed in data/sources.json into a new directory and check each sha256.

Usage: python3 -I -B tools/get_data.py <raw dir>

The SBA files are replaced each quarter and the FDIC list changes daily, so a later download may not match its pinned
hash; the script says which ones differ and keeps going, and the study then runs on the newer copy.
"""
import hashlib
import json
import sys
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent


def main():
    raw = Path(sys.argv[1]).resolve()
    spec = json.loads((ROOT / "data" / "sources.json").read_text(encoding="utf-8"))
    bad = []
    for f in spec["files"]:
        dst = raw / f["dir"] / f["file"]
        dst.parent.mkdir(parents=True, exist_ok=True)
        if not dst.exists():
            req = urllib.request.Request(f["url"], headers={"User-Agent": "loan-data-conversion study"})
            with urllib.request.urlopen(req, timeout=600) as r, open(dst, "wb") as out:
                while True:
                    chunk = r.read(1 << 20)
                    if not chunk:
                        break
                    out.write(chunk)
        h = hashlib.sha256(dst.read_bytes()).hexdigest()
        ok = h == f["sha256"]
        if not ok:
            bad.append(f["file"])
        print(f"{'ok ' if ok else 'NEW'} {f['file']} {dst.stat().st_size:,} bytes")
    for z in ("hmda_2017_mt_all-records_labels.zip", "hmda_2017_panel.zip"):
        import zipfile
        with zipfile.ZipFile(raw / "hmda" / z) as zf:
            zf.extractall(raw / "hmda")
    print(f"{len(spec['files']) - len(bad)} of {len(spec['files'])} files match their pinned sha256"
          + (f"; differ: {', '.join(bad)}" if bad else ""))


if __name__ == "__main__":
    main()
