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

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

ok() { PASS=$((PASS+1)); printf '  ok   %s\n' "$1"; }
bad() { FAIL=$((FAIL+1)); printf '  FAIL %s\n     %s\n' "$1" "$2"; }

mkfixture() {
  local dir
  dir="$(mktemp -d "/tmp/opencode-session-XXXX")"
  mkdir -p "$dir/wrappers/lib" "$dir/bin" "$dir/home/Projects/mega-plan-harness/tmp/logs"
  cp "$ROOT/wrappers/opencode.sh" "$dir/wrappers/opencode.sh"
  cp "$ROOT/wrappers/lib/finalize.sh" "$dir/wrappers/lib/finalize.sh"
  cp "$ROOT/wrappers/lib/usage-event.py" "$dir/wrappers/lib/usage-event.py"
  cp "$ROOT/wrappers/lib/verdict-status.py" "$dir/wrappers/lib/verdict-status.py"
  chmod +x "$dir/wrappers/opencode.sh"
  printf '%s\n' "$dir"
}

write_mock_opencode() {
  local dir="$1"
  cat > "$dir/bin/opencode" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

log_file="${MOCK_LOG_FILE:?}"
printf '%s\n' "$*" >> "$log_file"

if [[ "${1:-}" == "models" ]]; then
  printf '%s\n' "${MOCK_MODELS_OUTPUT:-opencode/deepseek-v4-flash-free}"
  exit "${MOCK_MODELS_EXIT_CODE:-0}"
fi

if [[ "${1:-}" == "run" ]]; then
  if [[ -n "${MOCK_RUN_OUTPUT+x}" ]]; then
    printf '%s\n' "$MOCK_RUN_OUTPUT"
  else
    printf '%s\n' '{"verdict":"PASS","findings":[]}'
  fi
  exit "${MOCK_RUN_EXIT_CODE:-0}"
fi

exit 2
EOF
  chmod +x "$dir/bin/opencode"
}

run_missing_arg_case() {
  local label="$1"
  shift
  local extra_args=("$@")
  local dir out rc
  dir="$(mkfixture)"
  write_mock_opencode "$dir"
  : > "$dir/invocations.log"

  local -a args=()
  local arg
  for arg in "${extra_args[@]}"; do
    if [[ "$arg" == "PLACEHOLDER" ]]; then
      args+=("$dir")
    else
      args+=("$arg")
    fi
  done

  if out=$(
    PATH="$dir/bin:$PATH" \
    _OPENCODE_ENGINE_BIN="$dir/bin/opencode" \
    MOCK_LOG_FILE="$dir/invocations.log" \
    HOME="$dir/home" \
    "$dir/wrappers/opencode.sh" "${args[@]}" 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  if [[ "$rc" -eq 2 ]]; then
    ok "$label exits 2"
  else
    bad "$label exits 2" "rc=$rc out=${out:-<empty>}"
  fi

  if [[ -s "$dir/invocations.log" ]]; then
    bad "$label does not dispatch" "$(cat "$dir/invocations.log")"
  else
    ok "$label does not dispatch"
  fi

  rm -rf "$dir"
}

run_missing_binary_case() {
  local dir out rc
  dir="$(mkfixture)"
  : > "$dir/invocations.log"

  if out=$(
    PATH="/usr/bin:/bin" \
    _OPENCODE_ENGINE_BIN="$dir/bin/missing-opencode" \
    MOCK_LOG_FILE="$dir/invocations.log" \
    HOME="$dir/home" \
    "$dir/wrappers/opencode.sh" \
      --workspace "$dir" \
      --trust "hi" \
      --task-slug "missing-bin" \
      --model "opencode/deepseek-v4-flash-free" \
      --timeout 10 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  if [[ "$rc" -eq 3 ]]; then
    ok "missing opencode binary exits 3"
  else
    bad "missing opencode binary exits 3" "rc=$rc out=${out:-<empty>}"
  fi

  if [[ -s "$dir/invocations.log" ]]; then
    bad "missing opencode binary does not dispatch" "$(cat "$dir/invocations.log")"
  else
    ok "missing opencode binary does not dispatch"
  fi

  rm -rf "$dir"
}

run_dispatch_case() {
  local dir out rc log_file cmd_line stream_line
  dir="$(mkfixture)"
  write_mock_opencode "$dir"
  log_file="$dir/invocations.log"
  : > "$log_file"

  if out=$(
    PATH="$dir/bin:$PATH" \
    _OPENCODE_ENGINE_BIN="$dir/bin/opencode" \
    MOCK_LOG_FILE="$log_file" \
    MOCK_RUN_OUTPUT='{"verdict":"PASS","findings":[]}' \
    HOME="$dir/home" \
    "$dir/wrappers/opencode.sh" \
      --workspace "$dir" \
      --trust "review this" \
      --task-slug "task-1" \
      --model "opencode/deepseek-v4-flash-free" \
      --timeout 30 2>&1
  ); then
    rc=0
  else
    rc=$?
  fi

  if [[ "$rc" -eq 0 ]]; then
    ok "dispatch exits zero"
  else
    bad "dispatch exits zero" "rc=$rc out=${out:-<empty>}"
  fi

  if grep -Fq -- '--model opencode/deepseek-v4-flash-free' "$log_file" \
    && grep -Fq -- '--dangerously-skip-permissions' "$log_file"; then
    ok "dispatch pins model and auto-approve flags"
  else
    bad "dispatch pins model and auto-approve flags" "$(cat "$log_file")"
  fi

  log_file="$(find "$dir/home/Projects/mega-plan-harness/tmp/logs" -name '*-task-1.log' | head -n 1 || true)"
  cmd_line="$(grep '^=== CMD:' "$log_file" || true)"
  if [[ "$cmd_line" == *'--model opencode/deepseek-v4-flash-free'* ]]; then
    ok "CMD header pins the same model as dispatch"
  else
    bad "CMD header pins the same model as dispatch" "${cmd_line:-<missing>}"
  fi

  stream_line="$(grep -F '{"verdict":"PASS","findings":[]}' "$log_file" || true)"
  if [[ -n "$stream_line" ]]; then
    ok "raw engine stream reaches logfile"
  else
    bad "raw engine stream reaches logfile" "$(cat "$log_file" 2>/dev/null || true)"
  fi

  rm -rf "$dir"
}

echo "opencode session wrapper:"
run_missing_arg_case "missing --workspace" --trust "hi" --task-slug "t1" --model "opencode/deepseek-v4-flash-free"
run_missing_arg_case "missing --trust" --workspace "PLACEHOLDER" --task-slug "t1" --model "opencode/deepseek-v4-flash-free"
run_missing_arg_case "missing --task-slug" --workspace "PLACEHOLDER" --trust "hi" --model "opencode/deepseek-v4-flash-free"
run_missing_arg_case "missing --model" --workspace "PLACEHOLDER" --trust "hi" --task-slug "t1"
run_missing_binary_case
run_dispatch_case
echo
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
