#!/usr/bin/env python3
"""One admitted candidate, exact golden A/B partition, retained producer receipts."""
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time

SHA = "b848244577d398600b59c7829fef9edbdb6315fa"
ROOT = Path("/home/reavus/projects/spt-core/spt-core")
TREE = ROOT / ".worktrees/consumer-linux-304-b8482445"
PROOF = ROOT / ".spt/preserved/304-handoff/consumer-linux"
TARGET = TREE / "target"
FLOOR = 32 * 1024**3
ENV = dict(os.environ)
ENV.update(PATH="/home/reavus/.cargo/bin:" + ENV["PATH"], CARGO_BUILD_JOBS="2",
           CARGO_TARGET_DIR=str(TARGET), CARGO_INCREMENTAL="0",
           RUSTFLAGS="-C link-arg=-fuse-ld=mold", NEXTEST_PROFILE="default",
           SPT_TEST_EPHEMERAL_ADVISORY_PORTS="1", SPT_ATTACH_GATE_WATCHDOG_MS="120000",
           SPT_ATTACH_IPC_DEADLINE_MS="30000", CARGO_TERM_COLOR="never", CI="true")
for name in ("CARGO_ENCODED_RUSTFLAGS", "NEXTEST_TEST_THREADS", "NEXTEST_RETRIES"):
    ENV.pop(name, None)
START = datetime.datetime.now(datetime.timezone.utc).isoformat()


def utc():
    return datetime.datetime.now(datetime.timezone.utc).isoformat()


def save(name, value):
    (PROOF / name).write_text(json.dumps(value, indent=2) + "\n")


def source_guard():
    head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=TREE, text=True).strip()
    status = subprocess.check_output(["git", "status", "--porcelain=v1", "--untracked-files=all"], cwd=TREE, text=True)
    if head != SHA or status:
        raise RuntimeError(f"SOURCE_REFUSED head={head} expected={SHA} status={status!r}")
    return {"sha": head, "clean": True}


def census():
    active = []
    owned = []
    for directory in Path("/proc").iterdir():
        if not directory.name.isdigit():
            continue
        try:
            name = (directory / "comm").read_text().strip()
            exe = os.readlink(directory / "exe")
            row = {"pid": int(directory.name), "name": name, "exe": exe,
                   "cmd": (directory / "cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace"),
                   "stat": (directory / "stat").read_text()}
            if any(word in name for word in ("cargo", "rustc", "nextest", "Runner.Worker")) or "/deps/" in exe:
                active.append(row)
            if exe.startswith(str(TARGET) + "/"):
                owned.append(row)
        except (OSError, PermissionError):
            pass
    return {"utc": utc(), "free_bytes": shutil.disk_usage(TREE).free,
            "load": os.getloadavg(), "active": active, "owned_survivors": owned}


def admit(label):
    state = {**source_guard(), **census()}
    save(label + "-admission.json", state)
    if state["free_bytes"] < FLOOR or state["active"] or state["owned_survivors"]:
        raise RuntimeError("RESOURCE_REFUSED " + json.dumps(state))
    return state


def run(label, argv):
    started = utc()
    clock = time.monotonic()
    path = PROOF / (label + ".log")
    print(f"BEGIN {label} sha={SHA} utc={started} argv={json.dumps(argv)}", flush=True)
    with path.open("x") as stream:
        result = subprocess.run(argv, cwd=TREE, env=ENV, stdout=stream, stderr=subprocess.STDOUT)
    text = path.read_text(errors="replace")
    summaries = [line.strip() for line in text.splitlines() if re.search(r"\bSummary\b", line)]
    receipt = {"sha": SHA, "command": argv, "start_utc": started, "end_utc": utc(),
               "elapsed_s": round(time.monotonic() - clock, 3), "exit": result.returncode,
               "summary_lines": summaries, "log": str(path),
               "log_sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
    save(label + "-receipt.json", receipt)
    print("END " + label + " " + json.dumps(receipt), flush=True)
    return receipt


phases = []
claimed = False
try:
    admit("start")
    workflow = TREE / ".github/workflows/golden.yml"
    lines = [line for line in workflow.read_text().splitlines() if re.match(r"^\s+HEAVY:", line)]
    assert len(lines) == 1, "HEAVY must have exactly one hoisted definition"
    match = re.fullmatch(r"      HEAVY: '(.*)'", lines[0])
    assert match is not None and "''" not in match[1], "unexpected HEAVY scalar shape"
    heavy = match[1]
    ENV["HEAVY"] = heavy
    (PROOF / "heavy-source-line.txt").write_text(lines[0] + "\n")
    (PROOF / "heavy.txt").write_text(heavy + "\n")
    save("environment.json", {key: ENV[key] for key in (
        "CARGO_BUILD_JOBS", "CARGO_TARGET_DIR", "CARGO_INCREMENTAL", "RUSTFLAGS", "NEXTEST_PROFILE",
        "SPT_TEST_EPHEMERAL_ADVISORY_PORTS", "SPT_ATTACH_GATE_WATCHDOG_MS", "SPT_ATTACH_IPC_DEADLINE_MS", "HEAVY")})
    runner_temp = PROOF / "runner-temp"
    runner_temp.mkdir(exist_ok=False)
    github_env = PROOF / "temp.env"
    assert not github_env.exists()
    ENV.update(RUNNER_TEMP=str(runner_temp), GITHUB_ENV=str(github_env), GITHUB_RUN_ID="304-b8482445", GITHUB_RUN_ATTEMPT="1")
    setup = run("temp-setup", ["bash", ".github/ci/test-temp-sandbox.sh", "setup"])
    assert setup["exit"] == 0
    for line in github_env.read_text().splitlines():
        key, value = line.split("=", 1)
        ENV[key] = value
    claim = run("pool-claim", ["cargo", "run", "-p", "xtask", "--", "pool-claim", "--pool", str(TARGET), "--label", "todlando-304-linux-b8482445"])
    assert claim["exit"] == 0
    claimed = True
    fixtures = [
        ["cargo", "build", "-p", "mock-adapter", "--bin", "mock-session"],
        ["cargo", "build", "-p", "mock-adapter", "--bin", "mock-shell"],
        ["cargo", "build", "-p", "mock-adapter", "--bin", "capture-player"],
        ["cargo", "build", "-p", "mock-adapter", "--bin", "console-mode-probe"],
        ["cargo", "build", "-p", "spt-daemon", "--bin", "service_fixture"],
        ["cargo", "build", "--workspace"],
    ]
    for index, argv in enumerate(fixtures, 1):
        admit(f"fixture-{index}")
        assert run(f"fixture-{index}", argv)["exit"] == 0
    for name, expression in (("phase-a", "not ( " + heavy + " )"), ("phase-b", heavy)):
        admit(name)
        receipt = run(name, ["cargo", "nextest", "run", "--workspace", "--no-fail-fast", "-E", expression])
        receipt["source_after"] = source_guard()
        phases.append(receipt)
        save("phases.json", phases)
    final = {"sha": SHA, "start_utc": START, "end_utc": utc(), "phases": phases, "final": census()}
    save("receipt.json", final)
    print("CONSUMER_DONE " + json.dumps({"sha": SHA, "exits": [r["exit"] for r in phases]}), flush=True)
except BaseException as error:
    save("driver-error.json", {"sha": SHA, "start_utc": START, "end_utc": utc(), "error": repr(error), "phases": phases, "census": census()})
    raise
finally:
    if claimed:
        run("pool-release", [str(TARGET / "debug/xtask"), "pool-release", "--pool", str(TARGET)])
    save("final-census.json", census())
sys.exit(0 if len(phases) == 2 and all(row["exit"] == 0 for row in phases) else 1)
