# SPDX-License-Identifier: GPL-3.0-only
# RDCalc adaptation, 2026-09-21. See README.txt and LICENSE.txt.
"""Reproduce the published numerical subsets using Python 3's standard library.

Run from any directory: python3 rebuild.py --check
Omit --check to write JSON into the adjacent data/ directory.
"""

import argparse
import csv
import hashlib
import io
import json
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true", help="verify without writing")
    args = parser.parse_args()
    root = Path(__file__).resolve().parent
    manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
    for source in manifest["sources"]:
        original = (root / source["originalFile"]).read_bytes()
        if hashlib.sha256(original).hexdigest() != source["sourceSha256"]:
            raise ValueError(f"Original source hash mismatch: {source['id']}")
        rows = []
        for row in csv.DictReader(io.StringIO(original.decode("utf-8")), delimiter="\t"):
            if source["key"] == "age" and not 0 <= float(row["age"]) <= 730:
                continue
            rows.append([float(row[key]) for key in ("sex", source["key"], "l", "m", "s")])
        output = (json.dumps(rows, separators=(",", ":"), allow_nan=False) + "\n").encode()
        if len(rows) != source["rows"] or hashlib.sha256(output).hexdigest() != source["assetSha256"]:
            raise ValueError(f"Rebuilt data mismatch: {source['id']}")
        target = root / source["assetFile"]
        if args.check:
            if target.read_bytes() != output:
                raise ValueError(f"Published data differs: {source['id']}")
        else:
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes(output)
        print(f"Verified {source['id']}: {len(rows)} rows")


if __name__ == "__main__":
    main()
