"""Observe local Linux namespace operations, not crashes or concurrency.

Usage: python3 observe.py --output observation.json [--directory /chosen/filesystem]
Requires Linux, a C compiler, accessible procfs and supported filesystem operations.
A failed/unsupported operation aborts without writing a success artifact.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import subprocess
import tempfile
from datetime import datetime, timezone

HERE = Path(__file__).resolve().parent

def observe(directory=None):
    source = HERE / "demo.c"
    with tempfile.TemporaryDirectory(prefix="hesela-tmpfile-", dir=directory) as tmp:
        root = Path(tmp)
        binary = root / "demo"
        flags = ["-std=c11", "-Wall", "-Wextra", "-Werror", "-O2"]
        subprocess.run(["cc", *flags, str(source), "-o", str(binary)], check=True)
        runs = []
        for i in range(3):
            case = root / ("run-" + str(i))
            case.mkdir(mode=0o700)
            result = subprocess.run([str(binary), str(case)], capture_output=True, text=True)
            if result.returncode:
                raise RuntimeError("Observation failed; no passing artifact: " + result.stderr)
            runs.append(json.loads(result.stdout))
        if any(run != runs[0] for run in runs[1:]):
            raise RuntimeError("Repeated observations differ")
        filesystem = subprocess.check_output(
            ["findmnt", "-n", "-o", "FSTYPE", "-T", str(root)], text=True).strip()
    return {
        "schemaVersion": 1,
        "evidenceType": "local-linux-api-observation",
        "generatedAt": datetime.now(timezone.utc).isoformat(),
        "environment": {
            "kernel": platform.release(), "machine": platform.machine(),
            "libc": list(platform.libc_ver()), "filesystem": filesystem,
            "python": platform.python_version(), "effectiveUid": os.geteuid(),
            "compiler": subprocess.check_output(["cc", "--version"], text=True).splitlines()[0],
            "compilerFlags": flags,
        },
        "repetitions": len(runs),
        "identicalAcrossRepetitions": True,
        "sourcesSha256": {
            name: hashlib.sha256((HERE / name).read_bytes()).hexdigest()
            for name in ["demo.c", "observe.py"]
        },
        "method": "Three sequential runs in fresh private directories on one filesystem; assertions compare syscall returns, contents, inode identity and link counts.",
        "limits": [
            "No concurrent readers or writers, network mounts, injected failures or crashes were tested.",
            "Successful fsync calls are not a power-loss durability experiment.",
            "The run checks local outcomes, not the atomicity contract under concurrency.",
            "Unsupported operations fail the run rather than count as successful observations.",
        ],
        "cases": runs[0]["cases"],
    }

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--directory")
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    result = observe(args.directory)
    args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    print(f"Observed {len(result['cases'])} cases x {result['repetitions']} runs on {result['environment']['filesystem']}")
