#!/usr/bin/env bash
set -u

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
EVIDENCE="$ROOT/evidence/task-9-claude-smoke.txt"
SESSION="lazyclaude-plugin-smoke-inner-$$"

mkdir -p "$ROOT/evidence"
: > "$EVIDENCE"

cleanup() {
  if command -v tmux >/dev/null 2>&1; then
    tmux kill-session -t "$SESSION" >/dev/null 2>&1 || true
  fi
}
trap cleanup EXIT INT TERM

{
  echo "LazyClaude Claude Code smoke"
  echo "ROOT: $ROOT"
  date
} >> "$EVIDENCE"

if ! command -v claude >/dev/null 2>&1; then
  {
    echo "CONTROLLED_SKIP: claude executable unavailable"
    echo "CLEANUP: no tmux session started"
  } >> "$EVIDENCE"
  echo "CONTROLLED_SKIP: claude executable unavailable"
  exit 0
fi

CLAUDE_VERSION="$(claude --version 2>&1 || true)"
echo "CLAUDE_VERSION: $CLAUDE_VERSION" >> "$EVIDENCE"

if ! command -v tmux >/dev/null 2>&1; then
  HELP_OUTPUT="$(claude --plugin-dir "$ROOT/plugins/lazyclaude" --help 2>&1 || true)"
  {
    echo "CONTROLLED_SKIP: tmux unavailable"
    echo "$HELP_OUTPUT" | sed -n '1,40p'
    echo "CLEANUP: no tmux session started"
  } >> "$EVIDENCE"
  echo "CONTROLLED_SKIP: tmux unavailable"
  exit 0
fi

tmux new-session -d -s "$SESSION" "cd '$ROOT' && claude --plugin-dir ./plugins/lazyclaude --help; printf '\nINNER_STATUS:%s\n' \"\$?\"; sleep 5"
sleep 1
tmux capture-pane -pt "$SESSION" -S -200 >> "$EVIDENCE" 2>&1 || true
tmux kill-session -t "$SESSION" >/dev/null 2>&1 || true

if rg -q "INNER_STATUS:0|Usage|Claude Code" "$EVIDENCE"; then
  echo "SMOKE_PASS: claude --plugin-dir accepted local LazyClaude plugin path" >> "$EVIDENCE"
  echo "CLEANUP: $SESSION killed" >> "$EVIDENCE"
  echo "SMOKE_PASS: claude --plugin-dir accepted local LazyClaude plugin path"
else
  echo "CONTROLLED_SKIP: claude help did not expose a stable plugin-dir smoke result" >> "$EVIDENCE"
  echo "CLEANUP: $SESSION killed" >> "$EVIDENCE"
  echo "CONTROLLED_SKIP: claude help did not expose a stable plugin-dir smoke result"
fi
