"""Download the eight benchmark instances this study uses from the benchmark's own site and check each file's sha256
against data/checksums.json. A file whose checksum does not match is deleted and the script fails. The files are plain
text and are only parsed, never run.

Usage: python3 -I -B tools/get_instances.py <empty or new directory>
"""
import hashlib
import json
import os
import sys
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
BASE = "https://www.schedulingbenchmarks.org/nrp/data/"


def main():
    out = Path(sys.argv[1])
    out.mkdir(parents=True, exist_ok=True)
    pins = json.loads((ROOT / "data" / "checksums.json").read_text(encoding="utf-8"))["files"]
    bad = 0
    for name, want in pins.items():
        p = out / name
        if not p.exists():
            with urllib.request.urlopen(BASE + name, timeout=120) as r:
                p.write_bytes(r.read())
        got = hashlib.sha256(p.read_bytes()).hexdigest()
        if got != want:
            print(f"{name}: checksum does not match; deleted")
            os.unlink(p)
            bad += 1
        else:
            print(f"{name}: ok")
    print(f"VERDICT: {'PASS' if not bad else 'FAIL'} ({len(pins) - bad} of {len(pins)} files match)")
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())
