#!/usr/bin/env bash
set -euo pipefail

tmp_dir="$(mktemp -d)"
cleanup() {
  rm -rf "$tmp_dir"
}
trap cleanup EXIT

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

assert_grep() {
  local pattern="$1"
  local file="$2"
  local message="$3"

  if ! grep -q -- "$pattern" "$file"; then
    echo "$message" >&2
    echo "--- output ---" >&2
    cat "$file" >&2
    exit 1
  fi
}

source_repo="${tmp_dir}/source"
mkdir -p "$source_repo/templates" "$source_repo/scripts"
cp -R "${repo_dir}/templates/CONTEXT.md" "${source_repo}/templates/CONTEXT.md"
cp -R "${repo_dir}/templates/docs" "${source_repo}/templates/docs"
cp -R "${repo_dir}/templates/scripts" "${source_repo}/templates/scripts"
cp -R "${repo_dir}/agentrail" "${source_repo}/agentrail"
cp "${repo_dir}/scripts/agentrail" "${source_repo}/scripts/agentrail"
cp "${repo_dir}/scripts/agentrail-legacy" "${source_repo}/scripts/agentrail-legacy"
cp "${repo_dir}/package.json" "${source_repo}/package.json"
chmod +x "${source_repo}/scripts/agentrail" "${source_repo}/scripts/agentrail-legacy"

git -C "$source_repo" init --initial-branch=main --quiet
git -C "$source_repo" config user.email agentrail@example.com
git -C "$source_repo" config user.name "AgentRail Test"

write_agentrail_state() {
  local state_file="${source_repo}/.agentrail/state.json"
  local active="${1:-0}"
  mkdir -p "$(dirname "$state_file")"

  if [[ "$active" == "1" ]]; then
    cat >"$state_file" <<'JSON'
{
  "schemaVersion": 1,
  "agentrailVersion": "0.0.0-test",
  "workflow": {
    "phase": "implementation",
    "activeIssue": 999,
    "activeRun": {
      "runId": "active-999",
      "targetType": "issue",
      "targetIssue": 999,
      "agent": "codex",
      "status": "running",
      "runDir": ".agentrail/runs/active-999",
      "metadataFile": ".agentrail/runs/active-999/run.json"
    },
    "completedRuns": [],
    "nextSuggestedAction": "Continue issue #999."
  }
}
JSON
  else
    cat >"$state_file" <<'JSON'
{
  "schemaVersion": 1,
  "agentrailVersion": "0.0.0-test",
  "workflow": {
    "phase": "idle",
    "activePhase": null,
    "activeIssue": null,
    "activePullRequest": null,
    "activePrd": null,
    "activeMilestone": null,
    "activeRun": null,
    "completedRuns": [],
    "lastCompletedStep": null,
    "nextSuggestedAction": "Pick a ready-for-agent issue."
  }
}
JSON
  fi
}

git -C "$source_repo" add agentrail package.json templates scripts
git -C "$source_repo" commit --quiet -m "seed source repo"
write_agentrail_state 0

set +e
env -u AGENTRAIL_ALLOW_SOURCE_RUN "${source_repo}/scripts/agentrail" run issue 4242 --target "$source_repo" --command true >"${tmp_dir}/source-run-guard.out" 2>&1
status=$?
set -e
if [[ "$status" -eq 0 ]]; then
  echo "source checkout issue execution did not require explicit opt-in" >&2
  exit 1
fi
assert_grep "Refusing to run issue #4242 in the AgentRail source checkout" "${tmp_dir}/source-run-guard.out" "source run guard did not explain refusal"

origin="${tmp_dir}/origin.git"
git clone --quiet --bare "$source_repo" "$origin"
git -C "$source_repo" remote add origin "$origin"
git -C "$source_repo" fetch --quiet origin main

if [[ -e "${source_repo}/scripts/ralph-loop" ]]; then
  echo "source dogfood fixture unexpectedly has root scripts/ralph-loop" >&2
  exit 1
fi

fake_bin="${tmp_dir}/fake-bin"
mkdir -p "$fake_bin"
cat >"${fake_bin}/gh" <<'GH'
#!/usr/bin/env bash
set -euo pipefail

case "$1 $2" in
  "label list")
    printf 'ready-for-agent\nafk\nafk-in-progress\nreview-fix\nmemory-suggestion\npr-reviewed\n'
    exit 0
    ;;
  "label create")
    printf 'label create %s\n' "$*" >>"${AFK_FAKE_GH_LOG:?}"
    exit 0
    ;;
  "issue edit")
    printf 'issue edit %s\n' "$*" >>"${AFK_FAKE_GH_LOG:?}"
    exit 0
    ;;
esac

echo "unexpected gh invocation: $*" >&2
exit 1
GH
chmod +x "${fake_bin}/gh"

agent_marker="${tmp_dir}/agent-marker.txt"
agent_command="${tmp_dir}/agent-command"
cat >"$agent_command" <<'AGENT'
#!/usr/bin/env bash
set -euo pipefail

prompt="$(cat)"
printf '%s\n' "$prompt" >>"${AFK_AGENT_MARKER:?}"
if grep -q "Handle exactly one issue: #4242" <<<"$prompt"; then
  exit 42
fi
AGENT
chmod +x "$agent_command"
mock_queue=$'4242\tDogfood source AFK\thttps://github.com/acme/repo/issues/4242\tafk,ready-for-agent'

set +e
AFK_WORKFLOW_MOCK_QUEUE="$mock_queue" \
AFK_WORKFLOW_REVIEW=0 \
AFK_AGENT_MARKER="$agent_marker" \
AFK_FAKE_GH_LOG="${tmp_dir}/gh.log" \
RALPH_AGENT_COMMAND="$agent_command" \
SOURCE_REPO="$source_repo" \
PATH="${fake_bin}:$PATH" \
  bash -c 'cd "$SOURCE_REPO" && templates/scripts/afk-workflow run --concurrency 1 --max-waves 1 --engine claude' >"${tmp_dir}/afk-real.out" 2>&1
status=$?
set -e

if [[ "$status" -eq 0 ]]; then
  echo "test AFK wave unexpectedly succeeded; expected configured agent command to stop after marker" >&2
  exit 1
fi

assert_grep "worker 1: issue #4242 Dogfood source AFK" "${tmp_dir}/afk-real.out" "AFK worker did not start selected issue"
if grep -q -- "missing workflow script: ralph-loop" "${tmp_dir}/afk-real.out"; then
  echo "AFK source dogfood still failed on missing ralph-loop" >&2
  cat "${tmp_dir}/afk-real.out" >&2
  exit 1
fi
if grep -q -- "missing AgentRail CLI" "${tmp_dir}/afk-real.out"; then
  echo "AFK source dogfood could not resolve AgentRail CLI" >&2
  cat "${tmp_dir}/afk-real.out" >&2
  exit 1
fi

[[ -s "$agent_marker" ]] || { echo "AFK worker did not reach configured agent execution" >&2; cat "${tmp_dir}/afk-real.out" >&2; exit 1; }
assert_grep "Handle exactly one issue: #4242" "$agent_marker" "Ralph prompt did not reach configured agent command"
agentrail_log="$(find "${source_repo}/.afk-workflow" -name 'issue-4242-agentrail.log' -print | head -1)"
[[ -n "$agentrail_log" ]] || { echo "AFK worker did not write AgentRail execution log" >&2; cat "${tmp_dir}/afk-real.out" >&2; exit 1; }
assert_grep "AgentRail run: issue #4242" "$agentrail_log" "AFK worker bypassed AgentRail issue execution"
assert_grep ".agentrail/runs" "$agentrail_log" "AgentRail execution log did not reference run artifacts"
assert_grep "AgentRail state: present" "$agent_marker" "AFK worker did not seed AgentRail state into the issue worktree"
worktree_state="$(find "${source_repo}/.afk-workflow" -path '*/worktrees/slot-1-issue-4242/.agentrail/state.json' -print | head -1)"
[[ -n "$worktree_state" ]] || { echo "AFK worker did not leave updated AgentRail state in the issue worktree" >&2; cat "${tmp_dir}/afk-real.out" >&2; exit 1; }
if [[ "$(node - "$worktree_state" <<'NODE'
const fs = require("fs");
const state = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
const workflow = state.workflow || {};
const run = Array.isArray(workflow.completedRuns) && workflow.completedRuns.find((item) => item.targetIssue === 4242);
console.log(Boolean(
  workflow.phase === "blocked" &&
  workflow.activeRun === null &&
  run &&
  run.status === "failed" &&
  run.metadataFile &&
  run.promptFile
));
NODE
)" != "true" ]]; then
  echo "AFK issue worktree state was not updated by AgentRail" >&2
  cat "$worktree_state" >&2
  exit 1
fi

(
  cd "$source_repo"
  AFK_WORKFLOW_MOCK_QUEUE="$mock_queue" templates/scripts/afk-workflow run --concurrency 1 --max-waves 1 --dry-run >"${tmp_dir}/source-dry-run.out"
)
assert_grep "dry-run: would run AgentRail issue execution" "${tmp_dir}/source-dry-run.out" "Source dry-run did not show AgentRail execution step"

write_agentrail_state 1
set +e
AFK_WORKFLOW_MOCK_QUEUE="$mock_queue" \
AFK_WORKFLOW_REVIEW=0 \
AFK_FAKE_GH_LOG="${tmp_dir}/gh.log" \
SOURCE_REPO="$source_repo" \
PATH="${fake_bin}:$PATH" \
  bash -c 'cd "$SOURCE_REPO" && templates/scripts/afk-workflow run --concurrency 1 --max-waves 1 --dry-run' >"${tmp_dir}/active-state.out" 2>&1
status=$?
set -e

if [[ "$status" -eq 0 ]]; then
  echo "AFK dry-run ignored active AgentRail state" >&2
  exit 1
fi
assert_grep "active AgentRail run exists for issue #999" "${tmp_dir}/active-state.out" "AFK did not check AgentRail state before selecting work"

echo "source AFK dogfood test passed"
