#!/usr/bin/env bash
# Regression for _human-session's direct systemd-run fallback path.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PASS=0; FAIL=0
ok() { PASS=$((PASS + 1)); printf 'PASS %s\n' "$1"; }
bad() { FAIL=$((FAIL + 1)); printf 'FAIL %s\n     %s\n' "$1" "$2"; }

TMP="$(mktemp -d "$HOME/.cache/human-session-fallback-test-XXXX")"
cleanup() { rm -rf "$TMP"; }
trap cleanup EXIT

mkdir -p "$TMP/bin" "$TMP/home/.claude/bin" "$TMP/launcher/bin" "$TMP/work" "$TMP/out"
cp "$ROOT/bin/_human-session" "$TMP/launcher/bin/_human-session"
chmod +x "$TMP/launcher/bin/_human-session"

cat >"$TMP/bin/systemd-run" <<'SYSTEMD_RUN'
#!/usr/bin/env bash
set -euo pipefail
while (( $# )); do
  if [[ "$1" == "--" ]]; then
    shift
    exec "$@"
  fi
  shift
done
exit 64
SYSTEMD_RUN
chmod +x "$TMP/bin/systemd-run"

cat >"$TMP/home/.claude/bin/tmpjail" <<'TMPJAIL'
#!/usr/bin/env bash
exec "$@"
TMPJAIL
chmod +x "$TMP/home/.claude/bin/tmpjail"

cat >"$TMP/work/helper.py" <<'PYTHON'
value = "loaded"
PYTHON
cat >"$TMP/work/runtime.py" <<'PYTHON'
#!/usr/bin/env python3
import os
from pathlib import Path
import helper

out = Path(os.environ["HS_OUT"])
(out / "python-pycache-prefix").write_text(os.environ["PYTHONPYCACHEPREFIX"])
(out / "unrelated").write_text(os.environ["HS_UNRELATED"])
(out / "helper").write_text(helper.value)
PYTHON
chmod +x "$TMP/work/runtime.py"

(
  cd "$TMP/work"
  HOME="$TMP/home" \
  PATH="$TMP/bin:$PATH" \
  HS_OUT="$TMP/out" \
  HS_UNRELATED="unchanged" \
  PYTHONPYCACHEPREFIX='%h/.cache/python-bytecode' \
  "$TMP/launcher/bin/_human-session" "$TMP/work/runtime.py"
) >"$TMP/fallback.log" 2>&1

if grep -Fq 'tmux config missing' "$TMP/fallback.log"; then
  ok "config-missing launch uses exec_without_tmux"
else
  bad "config-missing launch uses exec_without_tmux" "log=$(<"$TMP/fallback.log")"
fi

if [[ "$(<"$TMP/out/python-pycache-prefix")" == "$TMP/home/.cache/python-bytecode" ]]; then
  ok "fallback runtime receives absolute Python bytecode prefix"
else
  bad "fallback runtime receives absolute Python bytecode prefix" "prefix=$(<"$TMP/out/python-pycache-prefix")"
fi

if [[ "$(<"$TMP/out/unrelated")" == "unchanged" ]]; then
  ok "fallback preserves unrelated environment values"
else
  bad "fallback preserves unrelated environment values" "value=$(<"$TMP/out/unrelated")"
fi

if [[ ! -e "$TMP/work/%h" ]]; then
  ok "fallback runtime creates no cwd %h directory"
else
  bad "fallback runtime creates no cwd %h directory" "path=$TMP/work/%h"
fi

printf 'human-session-fallback: pass=%d fail=%d\n' "$PASS" "$FAIL"
(( FAIL == 0 ))
