#!/usr/bin/env python3
# Published reference script.
"""Split battery_n20.md into 20 question files, Q01 through Q20.

Usage:
    python3 split_battery.py battery_n20.md questions/
"""
from __future__ import annotations

import argparse
import hashlib
import pathlib
import re

EXPECTED = 20
FIRST = 1
LAST = 20


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("source", nargs="?", default="battery_n20.md")
    parser.add_argument("output", nargs="?", default="questions/")
    args = parser.parse_args()

    src = pathlib.Path(args.source)
    out = pathlib.Path(args.output)
    out.mkdir(parents=True, exist_ok=True)
    text = src.read_text(encoding="utf-8")
    parts = re.split(r"(?m)^# Question (\d+): (.*)$", text)
    written = []
    for i in range(1, len(parts), 3):
        number = int(parts[i])
        title = parts[i + 1].strip()
        body = parts[i + 2].strip()
        full = f"# Question {number}: {title}\n\n{body}\n"
        path = out / f"q{number:02d}.md"
        path.write_text(full, encoding="utf-8")
        digest = hashlib.sha256(full.encode("utf-8")).hexdigest()
        print(f"{path.name}  sha256={digest}  {title}")
        written.append(number)

    expected = list(range(FIRST, LAST + 1))
    if written != expected:
        raise SystemExit(f"ERROR: expected Q{FIRST:02d} through Q{LAST:02d}, got {written}")
    print(f"wrote {len(written)} files to {out}")


if __name__ == "__main__":
    main()
