#!/usr/bin/env python3
"""Fake `claude` CLI for executor tests.

Records how it was invoked (argv/env/stdin) into $CAIRN_TEST_SCRATCH and prints a
canned response framed by a STEP sentinel. Behaviour is steered purely through env
vars so the *real* invocation env (which is inv.env EXACTLY) is what drives it:

  CAIRN_TEST_SCRATCH  dir to write argv.json / env.json / stdin.txt into (required
                      for a normal run; absent for a bare --version probe)
  CAIRN_TEST_VERSION  string printed for `--version` (default below)
  CAIRN_TEST_SLEEP    seconds to sleep before responding (drives timeout tests)
  CAIRN_TEST_EXIT     exit code to return (default 0)
"""
import json
import os
import sys
import time
from pathlib import Path

_NAME = "claude"
_DEFAULT_VERSION = "claude 2.1.0 (fake)"

if "--version" in sys.argv:
    print(os.environ.get("CAIRN_TEST_VERSION", _DEFAULT_VERSION))
    sys.exit(0)

scratch = Path(os.environ["CAIRN_TEST_SCRATCH"])
scratch.mkdir(parents=True, exist_ok=True)
(scratch / "argv.json").write_text(json.dumps(sys.argv), encoding="utf-8")
(scratch / "env.json").write_text(json.dumps(dict(os.environ)), encoding="utf-8")
(scratch / "cwd.txt").write_text(os.getcwd(), encoding="utf-8")
(scratch / "stdin.txt").write_text(sys.stdin.read(), encoding="utf-8")

sleep_s = os.environ.get("CAIRN_TEST_SLEEP")
if sleep_s:
    time.sleep(float(sleep_s))

print(f"chatty {_NAME} preamble the sentinel must survive")
print('<<<STEP {"status": "done", "summary": "fake ok", "artifacts": []} STEP>>>')
sys.exit(int(os.environ.get("CAIRN_TEST_EXIT", "0")))
