#!/usr/bin/env python3
"""VIS synthetic reference mechanism v1. No model, network, daemon or general tool execution.
Owner-selected fresh scratch directory only. Not a hostile-filesystem sandbox.
"""
import argparse
import hashlib
import json
import os
import re
import stat
import sys
from datetime import datetime, timezone
from pathlib import Path

VERSION = "vis-west-door-1"
NOTES = [
    {"id": "N1", "kind": "task", "door": "north", "text": "Inspect the north door seal.", "fictional": True},
    {"id": "N2", "kind": "correction", "door": "west", "supersedes": "N1", "text": "Correction: inspect the west door seal instead of the north door seal.", "fictional": True},
    {"id": "N3", "kind": "draft_request", "permission": "pending", "text": "Draft a request for a door photo. Hold it for approval; do not send it.", "fictional": True},
]
def derive_candidate(notes):
    """Apply the fixed fixture's structured supersession, never instructions in prose."""
    original, correction, request = notes
    if correction["supersedes"] != original["id"] or request["permission"] != "pending":
        raise ValueError("invalid fixture source relationship")
    door = correction["door"]
    sources = [original["id"], correction["id"]]
    return {
        "format": VERSION,
        "current_fact": {"door": door, "sources": sources, "supersedes": original["id"]},
        "checklist": [{"task": "Inspect the " + door + " door seal", "status": "draft", "sources": sources}],
        "photo_request": {"status": "draft_unsent", "source": request["id"]},
        "pending_authority": ["photo-request-send"],
        "effects": [],
    }

EXPECTED = derive_candidate(NOTES)
POLICY = {"format": "vis-exercise-policy-1", "allowed_effect": "write_checklist", "approval_required": True, "outbound": False}
COORDINATE = {"format": "vis-coordinate-lock-1", "instance_name": "visitor-exercise", "mission": "Reconstruct the fictional west-door task only", "halt_boundary": "No outbound effects; stop on missing approval or invalid records", "kill_switch": "STOP file, red verification or nonzero error", "recovery": "Read START.md; inspect receipts; repair in a fresh authorized scratch directory"}

class Red(ValueError):
    pass

def encoded(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")

def digest(value):
    return "sha256:" + hashlib.sha256(encoded(value)).hexdigest()

def strict_pairs(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise Red("duplicate JSON key")
        result[key] = value
    return result

def parse(text):
    try:
        return json.loads(text, object_pairs_hook=strict_pairs, parse_constant=lambda _: (_ for _ in ()).throw(Red("nonfinite JSON")))
    except (ValueError, TypeError) as exc:
        raise Red("malformed or ambiguous JSON") from exc

def regular(path):
    path = Path(path).absolute()
    for parent in [path, *path.parents]:
        if parent.is_symlink():
            raise Red("symlink paths are not permitted")
    if not path.is_file() or not stat.S_ISREG(path.stat().st_mode) or path.stat().st_nlink != 1:
        raise Red("a regular, unlinked input file must exist")
    if path.stat().st_size > 1024 * 1024:
        raise Red("exercise file exceeds one MiB cap")
    return path

def load(path):
    return parse(regular(path).read_text(encoding="utf-8"))

def read_notes(path):
    lines = regular(path).read_text(encoding="utf-8").splitlines()
    if len(lines) != 3:
        raise Red("exactly three ordered source records required")
    notes = [parse(line) for line in lines]
    if encoded(notes) != encoded(NOTES):
        raise Red("expected exact ordered N1/N2/N3 fixture; sources are not instructions")
    return notes

def verify(notes_path, candidate_path):
    notes = read_notes(notes_path)
    candidate = load(candidate_path)
    if encoded(candidate) != encoded(derive_candidate(notes)):
        raise Red("candidate differs from exact source-backed fixture contract")
    return {"status": "verified_exercise", "source_hash": digest(notes), "candidate_hash": digest(candidate), "limits": "Synthetic structured result only; no model, permission sandbox or inspected door proved"}

# The in-page Check grades this two-line text view; door_check.py --text applies the same grammar.
TEXT_VIEW = (
    re.compile(r"^(?:-\s*)?\[ \]\s+Inspect the west door seal\. Sources: N1 corrected by N2\.$", re.I),
    re.compile(r"^(?:-\s*)?\[ \]\s+Draft a request for a door photo; sending remains unapproved\. Source: N3\.$", re.I),
)

def checklist_text(candidate):
    """Render the verified structured candidate as the two-line text view The Check grades."""
    if encoded(candidate) != encoded(EXPECTED):
        raise Red("only the verified fixture candidate has a text view")
    fact, request = candidate["current_fact"], candidate["photo_request"]
    return ("[ ] Inspect the " + fact["door"] + " door seal. Sources: " + fact["sources"][0] + " corrected by " + fact["sources"][1] + ".\n"
            "[ ] Draft a request for a door photo; sending remains unapproved. Source: " + request["source"] + ".\n")

def verify_text(notes_path, text_path):
    notes = read_notes(notes_path)
    raw = regular(text_path).read_text(encoding="utf-8")
    lines = [line.strip() for line in raw.replace("\r", "").strip().split("\n") if line.strip()]
    if len(lines) != 2 or not all(p.match(line) for p, line in zip(TEXT_VIEW, lines)):
        raise Red("text view differs from the door-check-v1 two-line grammar")
    return {"status": "verified_exercise_text", "source_hash": digest(notes), "candidate_hash": "sha256:" + hashlib.sha256(raw.encode("utf-8")).hexdigest(), "limits": "Synthetic two-line text view only; same grammar as the in-page Check; no model, permission sandbox or inspected door proved"}

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

def at(root, name):
    root = Path(root).absolute()
    for parent in [root, *root.parents]:
        if parent.is_symlink():
            raise Red("symlink roots are not permitted")
    if not root.is_dir():
        raise Red("initialize a fresh scratch directory first")
    p = root / name
    for parent in [p, *p.parents]:
        if parent.is_symlink():
            raise Red("symlink exercise paths are not permitted")
    if p.exists() and p.is_file() and p.stat().st_nlink != 1:
        raise Red("linked exercise paths are not permitted")
    return p

def save(root, name, value):
    p = at(root, name)
    p.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

def receipts(root):
    lines = regular(at(root, "ledger.jsonl")).read_text(encoding="utf-8").splitlines()
    previous = None
    rows = []
    keys = {"format", "sequence", "timestamp", "tool", "args_hash", "result_hash", "permission_decision", "status", "observation", "pending_authority", "previous_hash", "receipt_hash"}
    for i, line in enumerate(lines):
        row = parse(line)
        if not isinstance(row, dict) or set(row) != keys:
            raise Red("corrupt receipt schema")
        claimed = row["receipt_hash"]
        body = {k: v for k, v in row.items() if k != "receipt_hash"}
        if row["format"] != "vis-receipt-1" or type(row["sequence"]) is not int or row["sequence"] != i + 1 or row["previous_hash"] != previous or claimed != digest(body):
            raise Red("corrupt receipt chain")
        if row["pending_authority"] != ["photo-request-send"] or row["status"] not in ["not_run", "observed", "verified_exercise", "denied", "red", "stopped"]:
            raise Red("invalid receipt state")
        if not isinstance(row["permission_decision"], dict) or set(row["permission_decision"]) != {"decision", "scope", "basis"} or row["permission_decision"]["decision"] not in ["allow", "deny", "not_requested"]:
            raise Red("invalid permission receipt")
        rows.append(row)
        previous = claimed
    if not rows:
        raise Red("missing initialization receipt")
    return rows

def append(root, tool, args, result, status, decision="not_requested", basis="no execution authority requested"):
    p = at(root, "ledger.jsonl")
    rows = receipts(root) if p.stat().st_size else []
    row = {"format": "vis-receipt-1", "sequence": len(rows) + 1, "timestamp": stamp(), "tool": tool, "args_hash": digest(args), "result_hash": digest(result), "permission_decision": {"decision": decision, "scope": "synthetic outputs/checklist.json only", "basis": basis}, "status": status, "observation": result, "pending_authority": ["photo-request-send"], "previous_hash": rows[-1]["receipt_hash"] if rows else None}
    row["receipt_hash"] = digest(row)
    with p.open("a", encoding="utf-8") as stream:
        stream.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
        stream.flush()
        os.fsync(stream.fileno())
    return row

def checkpoint(status, proof=None):
    return {"format": "vis-checkpoint-1", "status": status, "instance_name": "visitor-exercise", "goal": "Fictional west-door checklist", "source_revision": digest(NOTES), "current_facts": [EXPECTED["current_fact"]] if proof else [], "pending_work": ["photo-request-draft"], "pending_authority": ["photo-request-send"], "permissions": [], "evidence": [proof] if proof else [], "next_step": "Read START.md; reconstruct before considering a new task", "restore_test": "not_run"}

def initialize(root):
    root = Path(root).absolute()
    for parent in [root, *root.parents]:
        if parent.is_symlink():
            raise Red("symlink initialization path forbidden")
    if root.exists() or not root.parent.is_dir():
        raise Red("choose a nonexistent directory inside an existing authorized scratch parent")
    root.mkdir()
    (root / "SOURCES").mkdir()
    (root / "outputs").mkdir()
    (root / "SOURCES/notes.jsonl").write_text("".join(json.dumps(n) + "\n" for n in NOTES), encoding="utf-8")
    (root / "ledger.jsonl").touch()
    (root / "PURPOSE.md").write_text("Fictional exercise only. No live door, message, model or daemon.\n", encoding="utf-8")
    (root / "START.md").write_text("At boot and each turn: check STOP; read coordinate.json; load host policy.json/configuration; read original SOURCES/notes.jsonl and its explicit N2 correction; validate ledger.jsonl; validate CHECKPOINT.json/evidence; reconstruct pending_authority and next task. Reconstruct with reference_loop.py status. STOP forbids task effects. Candidate is separate from verified output. Pending photo send remains denied. No model, fallback or network.\n", encoding="utf-8")
    save(root, "coordinate.json", COORDINATE)
    save(root, "policy.json", POLICY)
    save(root, "CHECKPOINT.json", checkpoint("not_run"))
    row = append(root, "initialize", {}, {"exercise": VERSION}, "not_run")
    return {"status": "not_run", "receipt_hash": row["receipt_hash"]}

def state(root):
    if encoded(load(at(root, "coordinate.json"))) != encoded(COORDINATE) or encoded(load(at(root, "policy.json"))) != encoded(POLICY):
        raise Red("exercise coordinate or policy modified")
    read_notes(at(root, "SOURCES/notes.jsonl"))
    rows = receipts(root)
    cp = load(at(root, "CHECKPOINT.json"))
    executions = [r for r in rows if r["tool"] == "write_checklist" and r["status"] == "verified_exercise"]
    expected_cp = checkpoint("verified_exercise", executions[-1]["receipt_hash"]) if executions else checkpoint("not_run")
    if encoded(cp) != encoded(expected_cp):
        raise Red("checkpoint inconsistent with verified ledger")
    if executions:
        result = verify(at(root, "SOURCES/notes.jsonl"), at(root, "outputs/checklist.json"))
        if executions[-1]["result_hash"] != digest(result):
            raise Red("output or receipt readback mismatch")
    elif at(root, "outputs/checklist.json").exists():
        raise Red("output exists without verified execution receipt")
    return rows, cp

def halted(root, rows):
    return at(root, "STOP").exists() or rows[-1]["status"] in ["red", "denied", "stopped"]

def stop(root):
    rows, _ = state(root)
    at(root, "STOP").write_text("Operator stopped this exercise. Inspect receipts; restart in fresh authorized scratch.\n", encoding="utf-8")
    append(root, "stop", {}, {"reason": "operator stop"}, "stopped")
    return {"status": "stopped"}

def propose(root):
    rows, _ = state(root)
    if halted(root, rows):
        raise Red("exercise halted; no new proposal")
    candidate = derive_candidate(read_notes(at(root, "SOURCES/notes.jsonl")))
    save(root, "candidate.json", candidate)
    append(root, "propose", {}, {"candidate_hash": digest(candidate), "not_executed": True}, "observed")
    return {"status": "proposed_not_executed", "notice": "Deterministic fixture proposal, not model inference"}

def execute(root, effect="write_checklist", approved=False):
    rows, _ = state(root)
    if halted(root, rows):
        raise Red("exercise halted; no effects")
    args = {"effect": effect}
    try:
        if effect != "write_checklist" or approved is not True:
            append(root, "gate", args, {"reason": "effect forbidden or explicit per-run approval missing"}, "denied", "deny", "fixed policy; operator approval absent or scope rejected")
            at(root, "STOP").write_text("Denied effect; no task effect executed.\n", encoding="utf-8")
            raise Red("effect denied; no checklist written; exercise halted")
        args["candidate_hash"] = digest(load(at(root, "candidate.json")))
        verify(at(root, "SOURCES/notes.jsonl"), at(root, "candidate.json"))
        save(root, "outputs/checklist.json", load(at(root, "candidate.json")))
        result = verify(at(root, "SOURCES/notes.jsonl"), at(root, "outputs/checklist.json"))
        row = append(root, "write_checklist", args, result, "verified_exercise", "allow", "explicit --approve-synthetic-write for this run only")
        save(root, "CHECKPOINT.json", checkpoint("verified_exercise", row["receipt_hash"]))
        return result
    except (ValueError, OSError, UnicodeError) as exc:
        # A denial already has its receipt. Verification / write failures halt too.
        if not at(root, "STOP").exists():
            at(root, "STOP").write_text("Red verification or tool failure; halted.\n", encoding="utf-8")
            append(root, "failure", args, {"reason": str(exc)}, "red", "deny", "verification or tool failed")
        raise

def status(root):
    rows, cp = state(root)
    return {"status": "halted" if halted(root, rows) else cp["status"], "current_facts": cp["current_facts"], "pending_authority": cp["pending_authority"], "photo_request": "draft_unsent", "receipt_count": len(rows), "restore_observation": "This process reconstructed persisted records; not a model restart or transfer"}

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=["init", "propose", "run", "status", "stop"])
    parser.add_argument("root", type=Path)
    parser.add_argument("--effect", default="write_checklist")
    parser.add_argument("--approve-synthetic-write", action="store_true")
    args = parser.parse_args()
    try:
        # Single operator, no concurrent writers. An exclusive lock refuses overlap.
        if args.command == "init":
            result = initialize(args.root)
        else:
            lock = at(args.root, ".exercise-lock")
            fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
            try:
                result = {"propose": lambda: propose(args.root), "run": lambda: execute(args.root, args.effect, args.approve_synthetic_write), "status": lambda: status(args.root), "stop": lambda: stop(args.root)}[args.command]()
            finally:
                os.close(fd)
                lock.unlink()
        print(json.dumps(result, ensure_ascii=False, sort_keys=True))
        return 0
    except (ValueError, OSError, UnicodeError) as exc:
        print("RED: " + str(exc), file=sys.stderr)
        return 1

if __name__ == "__main__":
    sys.exit(main())
