"""Read a pinned source checkout; emit descriptive counts and receipt arithmetic.

No training, network access, source mutation, or inference tests are performed.
The resulting JSON is a transcription audit, not an independent experiment.
"""

import argparse
import collections
import csv
import hashlib
import io
import json
import re
import statistics
import subprocess

SOURCE_COMMIT = "f39a3eec3a24a02c1e11d421d5752953e49d10db"


def summarize(values):
    mean = statistics.mean(values)
    sd = statistics.stdev(values)
    return {
        "n": len(values),
        "mean": round(mean, 9),
        "sample_sd": round(sd, 9),
        "range": round(max(values) - min(values), 9),
        "twice_sample_sd": round(2 * sd, 9),
        "cv_percent": round(100 * sd / mean, 6),
    }


def audit(repo):
    hashes = {}

    def read(path):
        data = subprocess.check_output(["git", "-C", repo, "show", f"{SOURCE_COMMIT}:{path}"])
        hashes[path] = hashlib.sha256(data).hexdigest()
        return data.decode("utf-8")

    results = list(csv.DictReader(io.StringIO(read("results.tsv")), delimiter="\t"))
    statuses = collections.Counter(row["status"] for row in results)
    if set(statuses) - {"keep", "discard", "crash"}:
        raise ValueError("Unexpected status in pinned source")
    receipts = subprocess.check_output([
        "git", "-C", repo, "ls-tree", "--name-only", f"{SOURCE_COMMIT}:docs/experiment_receipts"
    ]).decode().splitlines()
    program = read("program.md")
    read("docs/experiment_receipts/pack1_lost_keeps_20260705.md")
    no_op_rows = re.findall(r"^\| ([12]\. (?:QK-Norm|Logit softcap)) \| N/A \| N/A \| (NO-OP \(already in baseline\)) \|$", program, re.M)
    if len(no_op_rows) != 2:
        raise ValueError("Expected two first-wave no-op rows in the program summary")
    controls = {}
    for label, path in [
        ("untuned", "docs/experiment_receipts/seed_repeat_20260704.md"),
        ("tuned", "docs/experiment_receipts/seed_repeat_tuned_20260704.md"),
    ]:
        source = read(path)
        matches = re.findall(r"^\|\s*\d+\s*\|\s*(\d+)\s*\|\s*(0\.\d+|1\.\d+)\s*\|\s*([\d,]+)\s*\|", source, re.M)
        if len(matches) != 5:
            raise ValueError(f"Expected five control rows for {label}, got {len(matches)}")
        rows = [{"seed": int(seed), "val_bpb": float(value), "steps": int(steps.replace(",", ""))} for seed, value, steps in matches]
        controls[label] = {"source_path": path, "runs": rows, "recomputed": summarize([r["val_bpb"] for r in rows])}

    path = "docs/experiment_receipts/third_wave_20260704.md"
    source = read(path).split("### 3.2:", 1)[0]
    matches = re.findall(r"^\|\s*(\d+)\s*\|\s*(0\.\d+)\s*\|\s*([\d,]+)\s*\|", source, re.M)
    if len(matches) != 5:
        raise ValueError("Expected five BATCH 2x control rows")
    rows = [{"seed": int(seed), "val_bpb": float(value), "steps": int(steps.replace(",", ""))} for seed, value, steps in matches]
    controls["batch_2x"] = {"source_path": path, "runs": rows, "recomputed": summarize([r["val_bpb"] for r in rows])}

    path = "docs/experiment_receipts/pack2_nanochat_port_20260705.md"
    source = read(path)
    pack2 = []
    for section in re.split(r"^### ", source, flags=re.M)[1:]:
        heading = section.splitlines()[0]
        matches = re.findall(r"^\|\s*(\d+)\s*\|\s*(0\.\d+)\s*\|\s*(0\.\d+)\s*\|\s*\+?(0\.\d+)\s*\|", section, re.M)
        if len(matches) != 3:
            raise ValueError(f"Expected three seed comparisons: {heading}")
        rows = [{"seed": int(seed), "candidate_bpb": float(candidate), "baseline_bpb": float(base)} for seed, candidate, base, _ in matches]
        deltas = [r["candidate_bpb"] - r["baseline_bpb"] for r in rows]
        pack2.append({"heading": heading, "runs": rows, "mean_candidate_minus_baseline_bpb": round(statistics.mean(deltas), 9), "source_decision": "DISCARD"})
    if len(pack2) != 5:
        raise ValueError("Expected five Pack 2 candidate settings")
    return {
        "kind": "derived_source_audit_not_training_replication",
        "source_commit": SOURCE_COMMIT,
        "source_access": "Local author checkout inspected; full source and training logs are not bundled here.",
        "results_tsv": {"data_rows": len(results), "row_status_counts": dict(sorted(statuses.items())), "unit": "logged run row, not accepted patch"},
        "receipt_documents": len(receipts),
        "first_wave_no_op_entries": [{"candidate": name, "source_disposition": decision} for name, decision in no_op_rows],
        "controls": controls,
        "pack2": pack2,
        "source_sha256": dict(sorted(hashes.items())),
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source_repository", help="Local autoresearch-pipeline checkout containing the pinned commit")
    args = parser.parse_args()
    print(json.dumps(audit(args.source_repository), indent=2, ensure_ascii=True))
