"""Run reproducibility and thread-count examples for Chapter 9."""

from argparse import ArgumentParser
from datetime import datetime, timezone
from hashlib import sha256
from pathlib import Path
from statistics import NormalDist
from time import perf_counter
import csv
import json
import math
import subprocess

BOOK = Path(__file__).resolve().parents[1]
DOC = BOOK / "documents" / "ch09"


def write_new(path: Path, text: str):
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        if path.read_text(encoding="utf-8") != text:
            raise SystemExit(f"Refusing to replace changed fixture: {path}")
        return
    path.write_text(text, encoding="utf-8", newline="\n")


def benchmark_data(subjects=400):
    head = "ID,TIME,AMT,RATE,EVID,MDV,DV,CMT\n"
    rows = []
    for sid in range(1, subjects + 1):
        rows.append(f"{sid},0,100,0,1,1,0,1\n")
        for t in (0.25, 0.5, 1, 2, 4, 8, 12, 24):
            rows.append(f"{sid},{t:g},0,0,0,0,1,2\n")
    return head + "".join(rows)


def file_hash(path):
    return sha256(path.read_bytes()).hexdigest()


def type7(values, q):
    s = sorted(values)
    pos = q * (len(s) - 1)
    lo, hi = math.floor(pos), math.ceil(pos)
    return s[lo] if lo == hi else s[lo] + (pos - lo) * (s[hi] - s[lo])


def wilson(k, n, z):
    p, nf = k / n, float(n)
    den = 1 + z*z/nf
    centre = p + z*z/(2*nf)
    half = z * math.sqrt(p*(1-p)/nf + z*z/(4*nf*nf))
    return (max(0, (centre-half)/den), min(1, (centre+half)/den))


def main():
    ap = ArgumentParser()
    ap.add_argument("--nlmx", required=True, type=Path)
    ap.add_argument("--output", type=Path, default=DOC / "results")
    ns = ap.parse_args()
    exe, out = ns.nlmx.resolve(), ns.output.resolve()
    if BOOK.resolve() not in out.parents:
        raise SystemExit("Output must remain inside nlmx-book")
    if out.exists() and any(out.iterdir()):
        raise SystemExit(f"Choose a new output folder; existing results retained: {out}")
    write_new(DOC / "benchmark.csv", benchmark_data())
    logs = out / "logs"; logs.mkdir(parents=True)
    rel = lambda p: Path(p).resolve().relative_to(BOOK.resolve()).as_posix()
    commands, timings, hashes = [], [], {}

    def run(name, args):
        cmd = [str(exe), *args, "--no-color"]
        start = perf_counter()
        got = subprocess.run(cmd, cwd=BOOK, capture_output=True, text=True,
                             encoding="utf-8", errors="replace")
        elapsed = perf_counter() - start
        (logs / f"{name}.txt").write_text(
            "$ nlmx " + " ".join(args) + "\n\n" + got.stdout + got.stderr,
            encoding="utf-8", newline="\n")
        commands.append({"name": name, "args": args, "exit_code": got.returncode})
        if got.returncode != 0:
            raise RuntimeError(f"{name}: exit {got.returncode}")
        print(name, "exit 0", f"{elapsed:.3f}s", flush=True)
        return got, elapsed

    version, _ = run("version", ["version"])
    version_line = next((x.strip() for x in version.stdout.splitlines() if "v4." in x), "nlmx 4.3.0")
    for threads in (1, 2, 4):
        dest = out / f"threads-{threads}"
        args = ["sims", "documents/ch08/analytic.ctl", "--data", "documents/ch09/benchmark.csv",
                "--subproblems", "16", "--seed", "90901", "--threads", str(threads),
                "--no-plots", "--no-metrics", "-o", rel(dest)]
        _, elapsed = run(f"sims-threads-{threads}", args)
        timings.append({"threads": threads, "wall_seconds": elapsed,
                        "speedup_vs_1": None})
        hashes[str(threads)] = {
            "analytic_sim.csv": file_hash(dest / "analytic_sim.csv"),
            "analytic_subjects.csv": file_hash(dest / "analytic_subjects.csv"),
        }
    base = timings[0]["wall_seconds"]
    for x in timings:
        x["speedup_vs_1"] = base / x["wall_seconds"]
    if len({v["analytic_sim.csv"] for v in hashes.values()}) != 1:
        raise RuntimeError("simulated rows differ by thread count")
    if len({v["analytic_subjects.csv"] for v in hashes.values()}) != 1:
        raise RuntimeError("subject rows differ by thread count")

    reference = {
        "sha256_abc": sha256(b"abc").hexdigest(),
        "normal_quantile_0_975": NormalDist().inv_cdf(0.975),
        "type7_q25_1_to_8": type7(range(1, 9), 0.25),
        "wilson_5_of_10_95": wilson(5, 10, 1.959963984540054),
        "chi_square_1df_0_95_reference": 3.841458820694124,
    }
    summary = {
        "source_tree_version": "4.4.0",
        "evidence_executable": version_line,
        "created_utc": datetime.now(timezone.utc).isoformat(),
        "executable_sha256": file_hash(exe),
        "rng_derivation_version": 2,
        "seed": 90901,
        "subjects": 400,
        "subproblems": 16,
        "thread_count_outputs_identical": True,
        "stable_file_hashes_by_threads": hashes,
        "timings": timings,
        "reference_values": reference,
        "commands": commands,
    }
    (out / "example_summary.json").write_text(json.dumps(summary, indent=2) + "\n",
                                               encoding="utf-8", newline="\n")
    with (out / "thread_timings.csv").open("w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(timings[0])); w.writeheader(); w.writerows(timings)
    print(json.dumps({k: v for k, v in summary.items() if k not in ("commands", "stable_file_hashes_by_threads")}, indent=2))


if __name__ == "__main__":
    main()
