"""Compile and repeat isolated Linux mmap API checks; print JSON observations."""
import argparse
import datetime
import hashlib
import json
import pathlib
import platform
import subprocess
import tempfile


def run(command, **kwargs):
    return subprocess.run(command, check=True, capture_output=True, text=True,
                          timeout=60, **kwargs).stdout.strip()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repetitions", type=int, default=5)
    parser.add_argument("--temp-dir", type=pathlib.Path, default=None)
    args = parser.parse_args()
    if platform.system() != "Linux":
        parser.error("These observations target Linux, not a portable conformance suite.")
    if not 1 <= args.repetitions <= 100:
        parser.error("repetitions must be between 1 and 100")
    source = pathlib.Path(__file__).with_name("mmap-boundaries.c")
    compiler = run(["cc", "--version"]).splitlines()[0]
    with tempfile.TemporaryDirectory(prefix="hesela-mmap-", dir=args.temp_dir) as tmp:
        executable = pathlib.Path(tmp) / "mmap-boundaries"
        filesystem = run(["stat", "-f", "-c", "%T", tmp])
        flags = ["-std=c11", "-O2", "-Wall", "-Wextra", "-Werror"]
        run(["cc", *flags, str(source), "-o", str(executable)])
        observations = [json.loads(run([str(executable)], cwd=tmp))
                        for _ in range(args.repetitions)]
    if any(row != observations[0] for row in observations):
        raise RuntimeError("Repeated API observations disagree")
    result = {
        "schemaVersion": 1,
        "evidenceType": "measured-linux-api-behavior",
        "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "environment": {
            "system": platform.system(), "kernel": platform.release(),
            "machine": platform.machine(), "compiler": compiler,
            "filesystem": filesystem, "compileFlags": flags,
        },
        "sourceSha256": hashlib.sha256(source.read_bytes()).hexdigest(),
        "runnerSha256": hashlib.sha256(pathlib.Path(__file__).read_bytes()).hexdigest(),
        "repetitions": args.repetitions,
        "casesPerRepetition": 7,
        "allRepetitionsIdentical": True,
        "limitations": [
            "Single host and filesystem; deterministic examples, not a sampled population.",
            "Reads may use cache; no power loss, reboot, cache eviction or hardware verification.",
            "No concurrent writers, DAX, huge pages, partial-tail remapping or file-growth remapping.",
            "SIGBUS is induced only in a disposable child; files are temporary and immediately unlinked.",
        ],
        "observations": observations,
    }
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
