#!/usr/bin/env python3
"""Check synthetic exercise data only. Does not execute any sample content."""
from pathlib import Path
import json
import sys

BASE = Path(__file__).resolve().parent
MAX_BYTES = 65536

def read_text(name: str) -> str:
    p = BASE / name
    if p.is_symlink() or not p.is_file():
        raise ValueError(f"Expected a regular local file: {name}")
    with p.open("rb") as stream:
        raw = stream.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError(f"Exercise file is unexpectedly large: {name}")
    return raw.decode("utf-8")

def check(condition: bool, message: str) -> None:
    if not condition:
        raise ValueError(message)
    print("OK:", message)

def main() -> int:
    try:
        task = json.loads(read_text("tasks.json.txt"))
        check(task["command"] == "node" and task["args"] == ["webfonts/preview.woff2"],
              "task describes an interpreter and a font-like argument")
        check(task["runOptions"]["runOn"] == "folderOpen", "automatic trigger is described, not executed")
        a = bytes.fromhex(read_text("font-candidate-a.hex.txt"))
        b = bytes.fromhex(read_text("font-candidate-b.hex.txt"))
        check(a[:4] == b"wOF2", "A has only the expected four-byte signature")
        check(b[:4] != b"wOF2" and b.startswith(b"const "), "B fails the WOFF2 signature check")
        pkg = json.loads(read_text("package.json.txt"))
        check(pkg["scripts"]["postinstall"] == "npm start", "installation hook points to the start script")
        events = [json.loads(line) for line in read_text("events.jsonl").splitlines() if line]
        check(len(events) == 5 and {e["host"] for e in events} == {"lab-1"}, "five events belong to one synthetic host")
        check([e["time"] for e in events] == sorted(e["time"] for e in events), "event ordering is consistent")
        check(all(e.get("process") == "p17" for e in events[1:4]), "network and write events reference p17")
        check(events[-1]["parent"] == "p17" and events[-1]["command"].endswith(events[3]["path"]),
              "the child process refers to the written path")
        check(not any("response_body" in e or "secret_read" in e for e in events),
              "the exercise does not supply evidence of a response body or credential theft")
    except (OSError, UnicodeError, ValueError, KeyError, TypeError) as exc:
        print(f"Exercise validation failed: {exc}", file=sys.stderr)
        return 1
    print("This validates the exercise data, not the safety of any repository.")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
