"""Probe a pinned Eden header with stubbed callbacks, not an RDMA runtime.

Fetch the header from URL below, then:
python3 eden-hint-probe.py --header pgfault.h --output results.json
The external header is hash-checked, not redistributed by this harness.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import platform
import subprocess
import tempfile

REVISION = "beca12a7af20bc30de0a3aae1edd2570bb09cee2"
URL = "https://raw.githubusercontent.com/eden-farmem/eden/" + REVISION + "/inc/runtime/pgfault.h"
HEADER_SHA256 = "8cb570d5edcb15e2825fc49c461c38904efcf8fa6ae2e9e2395a07d50457fa43"
CASES = {
    "write_priority_no_pr": ("", "hint_write_fault_prio(&value, 2);"),
    "write_priority_captured_pr": ("int pr = 7; (void)pr;", "hint_write_fault_prio(&value, 2);"),
    "write_all_control": ("", "hint_write_fault_all(&value, 0, 2);"),
    "read_priority_control": ("", "hint_read_fault_prio(&value, 2);"),
}
PREAMBLE = """
#include <stdbool.h>
#include <stdio.h>
#include "pgfault.h"
static int seen_priority = -1;
static int calls = 0;
bool __is_fault_pending(void *address, bool write, bool hint_eviction) {
    (void)address; (void)write; (void)hint_eviction; return true;
}
void thread_park_on_fault(void *address, bool write, int rdahead, int evprio) {
    (void)address; (void)write; (void)rdahead; seen_priority = evprio; calls++;
}
"""

def check_result(row):
    if row["case"] not in CASES or row["define"] not in [None, "EDEN_HINTS", "REMOTE_MEMORY_HINTS"]:
        raise ValueError("Unknown probe configuration")
    enabled = row["define"] is not None
    failure = enabled and row["case"] == "write_priority_no_pr"
    if failure:
        if row["compile_exit"] == 0 or not all(word in row["stderr"] for word in ["pr", "undeclared"]) or row["run_exit"] is not None:
            raise ValueError("Expected the enabled undeclared-pr compile failure")
        return
    priority = -1 if not enabled else (7 if row["case"] == "write_priority_captured_pr" else 2)
    expected = f"{priority} {int(enabled)}\n"
    if row["compile_exit"] != 0 or row["run_exit"] != 0 or row["stdout"] != expected:
        raise ValueError(f"Unexpected callback result: {row}")

def fixture(name):
    declaration, call = CASES[name]
    code = PREAMBLE + "\nint main(void) {\nint value = 0; (void)value;\n" + declaration + "\n" + call
    return code + '\nprintf("%d %d\\n", seen_priority, calls); return 0;\n}\n'

def verify_report(report):
    if report["revision"] != REVISION or report["header_sha256"] != HEADER_SHA256 or report["header_url"] != URL:
        raise ValueError("Wrong source provenance")
    if report["harness_sha256"] != hashlib.sha256(Path(__file__).read_bytes()).hexdigest():
        raise ValueError("Report was generated by another harness")
    expected = {(case, define, opt) for case in CASES
                for define in [None, "EDEN_HINTS", "REMOTE_MEMORY_HINTS"] for opt in ["-O0", "-O2"]}
    actual = set()
    for row in report["cases"]:
        check_result(row)
        flags = row["flags"]
        if len(flags) < 5:
            raise ValueError("Missing compiler flags")
        opt = flags[4]
        wanted = ["-std=c11", "-Wall", "-Wextra", "-Werror", opt]
        if row["define"]:
            wanted.append("-D" + row["define"])
        if flags != wanted or row["fixture_sha256"] != hashlib.sha256(fixture(row["case"]).encode()).hexdigest():
            raise ValueError("Wrong flags or fixture")
        actual.add((row["case"], row["define"], opt))
    if actual != expected or len(report["cases"]) != len(expected):
        raise ValueError("Missing or duplicate configurations")

def run(header, cc="cc"):
    raw = Path(header).read_bytes()
    if hashlib.sha256(raw).hexdigest() != HEADER_SHA256:
        raise ValueError("Header hash does not match the reviewed revision")
    observations = []
    with tempfile.TemporaryDirectory(prefix="eden-hint-probe-") as temp:
        work = Path(temp)
        (work / "pgfault.h").write_bytes(raw)
        for optimization in ["-O0", "-O2"]:
            for define in [None, "EDEN_HINTS", "REMOTE_MEMORY_HINTS"]:
                for name in CASES:
                    code = fixture(name)
                    (work / "probe.c").write_text(code)
                    flags = ["-std=c11", "-Wall", "-Wextra", "-Werror", optimization]
                    if define:
                        flags.append("-D" + define)
                    compiled = subprocess.run([cc, *flags, "probe.c", "-o", "probe"],
                        cwd=work, text=True, capture_output=True, timeout=30)
                    executed = None
                    if compiled.returncode == 0:
                        executed = subprocess.run([str(work / "probe")], cwd=work,
                            text=True, capture_output=True, timeout=5)
                    row = dict(case=name, define=define, flags=flags,
                        compile_exit=compiled.returncode,
                        stderr="\n".join(line for line in compiled.stderr.splitlines() if "error:" in line),
                        run_exit=executed.returncode if executed else None,
                        stdout=executed.stdout if executed else None,
                        fixture_sha256=hashlib.sha256(code.encode()).hexdigest())
                    check_result(row)
                    observations.append(row)
    return dict(schema_version=1, kind="isolated-header-contract-probe",
        revision=REVISION, header_url=URL, header_sha256=HEADER_SHA256,
        generated_at=datetime.now(timezone.utc).isoformat(),
        harness_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        compiler=subprocess.check_output([cc, "--version"], text=True).splitlines()[0],
        platform=platform.platform(), cases=observations,
        scope="Only preprocessing, compilation and stub callback arguments; no Eden runtime, kernel, RDMA or performance replication.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--header")
    parser.add_argument("--cc", default="cc")
    parser.add_argument("--output", type=Path)
    parser.add_argument("--check", type=Path)
    args = parser.parse_args()
    if args.check:
        verify_report(json.loads(args.check.read_text()))
        print("24 pinned-header observations verified")
    else:
        if not args.header:
            parser.error("--header is required unless --check is used")
        result = run(args.header, args.cc)
        verify_report(result)
        report = json.dumps(result, indent=2) + "\n"
        if args.output:
            args.output.write_text(report)
        else:
            print(report, end="")
