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

repo_root() {
  local script_dir
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  if git -C "$script_dir" rev-parse --show-toplevel >/dev/null 2>&1; then
    git -C "$script_dir" rev-parse --show-toplevel
    return
  fi
  cd "$script_dir/../.." && pwd
}

root="$(repo_root)"
workflow_state_cmd="$root/ai/commands/workflow-state.sh"

field_value() {
  local label="$1"
  awk -F': ' -v label="$label" '$1 == label { print substr($0, length(label) + 3); exit }'
}

print_blockers_from_state() {
  local state_output="$1"
  local blockers
  blockers="$(printf '%s\n' "$state_output" | field_value "Blockers")"
  if [[ -n "$blockers" && "$blockers" != "None." && "$blockers" != "(not available)" ]]; then
    echo "Blockers:"
    echo "  $blockers"
    return
  fi

  case "$canonical_state" in
    ready_for_qa)
      printf '%s\n' "$state_output" |
        awk '
          /^Ready-for-QA blockers:/ { in_blockers = 1; next }
          /^$/ && in_blockers { exit }
          in_blockers { print }
        ' | sed 's/^/  /'
      ;;
    ready_to_complete | qa_passed)
      printf '%s\n' "$state_output" |
        awk '
          /^Ready-to-complete blockers:/ { in_blockers = 1; next }
          /^$/ && in_blockers { exit }
          in_blockers { print }
        ' | sed 's/^/  /'
      ;;
    *)
      echo "Blockers:"
      echo "  none reported by workflow-state"
      ;;
  esac
}

print_handoff() {
  local gate_checked="$1"
  local result="$2"
  local exact_command="$3"
  local review_command="$4"
  local approval="$5"
  local immediate_step="${6:-}"
  local immediate_command="${7:-}"
  local post_approval_command="${8:-}"
  local autopilot_continuation="${9:-}"

  echo "## Handoff"
  echo
  echo "- Canonical State: $canonical_state"
  echo "- Gate Checked: $gate_checked"
  echo "- Result: $result"
  echo "- Blockers: $blocker_summary"
  echo "- Recommended Next Action: $recommended_action"
  echo "- Exact Next Command: $exact_command"
  if [[ -n "$immediate_step" ]]; then
    echo "- Immediate Next Step: $immediate_step"
  fi
  if [[ -n "$immediate_command" ]]; then
    echo "- Immediate Next Command: $immediate_command"
  fi
  if [[ -n "$post_approval_command" ]]; then
    echo "- Post-Approval Command: $post_approval_command"
  fi
  if [[ -n "$autopilot_continuation" ]]; then
    echo "- Autopilot Continuation: $autopilot_continuation"
  fi
  if [[ -n "$review_command" ]]; then
    echo "- Optional Prompt Review Command: $review_command"
  fi
  echo "- Human Approval Needed: $approval"
}

if [[ -x "$workflow_state_cmd" ]]; then
  state_output="$("$workflow_state_cmd")"
  canonical_state="$(printf '%s\n' "$state_output" | field_value "Canonical state")"
  current_phase="$(printf '%s\n' "$state_output" | field_value "Current phase")"
  recommended_action="$(printf '%s\n' "$state_output" | field_value "Recommended next action")"
  blocker_summary="$(printf '%s\n' "$state_output" | field_value "Blockers")"
  active_chunk="$(printf '%s\n' "$state_output" | field_value "Active chunk")"

  [[ -n "$canonical_state" ]] || canonical_state="manual_intervention_required"
  [[ -n "$current_phase" ]] || current_phase="manual intervention required"
  [[ -n "$recommended_action" ]] || recommended_action="manual intervention required"
  [[ -n "$blocker_summary" ]] || blocker_summary="none reported by workflow-state"

  echo "Recommended Next Action"
  echo
  echo "Canonical state: $canonical_state"
  echo "Current phase: $current_phase"
  echo "Recommended next action: $recommended_action"
  echo
  print_blockers_from_state "$state_output"
  echo

  case "$canonical_state" in
    developer_pass)
      print_handoff "workflow-state" "needs_implementation" "ai/commands/prompt-synthesize.sh dev" "ai/commands/prompt-synthesize.sh review dev" "no"
      ;;
    ready_for_qa)
      print_handoff "workflow-state --ready-for-qa" "needs_review" "ai/commands/prompt-synthesize.sh qa" "ai/commands/prompt-synthesize.sh review qa" "no"
      ;;
    qa_blocked_fixable)
      print_handoff "workflow-state" "blocked_retry_safe" "ai/commands/prompt-synthesize.sh dev-fix" "ai/commands/prompt-synthesize.sh review dev-fix" "no" "" "" "" "Under approved Chunk Autopilot, synthesize/send the focused Developer fix, then continue to readiness and QA."
      ;;
    qa_blocked_requires_decision)
      print_handoff "workflow-state" "blocked_requires_decision" "ai/commands/workflow-summary.sh" "" "yes - resolve QA blocker classification, requirements ambiguity, or human decision before retry"
      ;;
    qa_blocked_scope_change)
      print_handoff "workflow-state" "blocked_scope_change" "ai/commands/workflow-summary.sh" "" "yes - approve scope change or create a new chunk before retry"
      ;;
    retry_limit_reached)
      print_handoff "workflow-state" "retry_limit_reached" "ai/commands/workflow-summary.sh" "" "yes - retry limit reached; human must decide whether to continue"
      ;;
    qa_passed)
      print_handoff "workflow-state --ready-to-complete" "completion_gate_blocked" "ai/commands/workflow-state.sh --ready-to-complete" "" "yes - Orchestrator must resolve completion blockers before archiving"
      ;;
    ready_to_complete)
      if [[ "$active_chunk" == ai/chunks/active/* ]]; then
        complete_command="ai/tools/operator-daemon/request-action.sh --action complete_chunk --target $active_chunk"
      else
        complete_command="ai/commands/workflow-state.sh --ready-to-complete"
      fi
      print_handoff "workflow-state --ready-to-complete" "ready_to_complete" "ai/commands/workflow-summary.sh" "" "yes - completion approval may be required; under approved Chunk Autopilot this is a pause, not a terminal stop" "Human review of completion-ready summary" "ai/commands/workflow-summary.sh" "$complete_command" "After approval, complete/archive this chunk, safely stage and commit approved files when policy allows, then activate/run the next approved queued chunk unless a stop condition or final review boundary applies."
      ;;
    commit_ready)
      print_handoff "workflow-state" "commit_ready" "git status --short --untracked-files=all && git diff --stat" "" "yes - human should review and commit approved changes unless an approved autopilot commit policy applies" "" "" "" "Under approved Chunk Autopilot, a safe commit is a continuation point; after commit, proceed to the next approved queued chunk unless a stop condition applies."
      ;;
    manual_intervention_required)
      shopt -s nullglob
      active_glob=("$root"/ai/chunks/active/chunk-[0-9]*-*.md)
      backlog_glob=("$root"/ai/chunks/backlog/chunk-[0-9]*-*.md)
      shopt -u nullglob
      IFS=$'\n' backlog_glob=($(printf '%s\n' "${backlog_glob[@]}" | sort))
      unset IFS
      if (( ${#active_glob[@]} == 0 && ${#backlog_glob[@]} > 0 )); then
        next_chunk="${backlog_glob[0]}"
        exact_command="ai/commands/activate-chunk.sh ${next_chunk#"$root/"}"
        print_handoff "workflow-state" "activate_backlog_chunk" "$exact_command" "" "yes - activate only after confirming this backlog chunk is still the intended next work"
        exit 0
      fi
      print_handoff "workflow-state" "manual_intervention_required" "ai/commands/workflow-state.sh" "" "yes - workflow state is ambiguous or unsafe to continue automatically"
      ;;
    *)
      print_handoff "workflow-state" "needs_manual_review" "ai/commands/workflow-state.sh" "" "yes - unrecognized or unsupported workflow state"
      ;;
  esac
  exit 0
fi

shopt -s nullglob
active_chunks=("$root"/ai/chunks/active/chunk-[0-9]*-*.md)
backlog_chunks=("$root"/ai/chunks/backlog/chunk-[0-9]*-*.md)
completed_chunks=("$root"/ai/chunks/completed/chunk-[0-9]*-*.md)
shopt -u nullglob

IFS=$'\n' active_chunks=($(printf '%s\n' "${active_chunks[@]}" | sort))
IFS=$'\n' backlog_chunks=($(printf '%s\n' "${backlog_chunks[@]}" | sort))
IFS=$'\n' completed_chunks=($(printf '%s\n' "${completed_chunks[@]}" | sort))
unset IFS

echo "Recommended Next Action"
echo

if (( ${#active_chunks[@]} > 1 )); then
  echo "Multiple active chunks are present. Pick one implementation thread or ask for manual orchestration before continuing:"
  for chunk in "${active_chunks[@]}"; do
    echo "  - $(basename "$chunk")"
  done
  exit 0
fi

if (( ${#active_chunks[@]} == 1 )); then
  active_chunk="${active_chunks[0]}"
  echo "Continue the active chunk:"
  echo "  $(basename "$active_chunk")"
  echo
  echo "Suggested loop:"
  echo "  1. Developer implements or addresses QA blockers."
  echo "  2. QA reviews and returns PASS or BLOCKED."
  echo "  3. Orchestrator completes only after QA PASS or human approval."
  exit 0
fi

if (( ${#backlog_chunks[@]} > 0 )); then
  next_chunk="${backlog_chunks[0]}"
  echo "Activate the next backlog chunk when ready:"
  echo "  ai/commands/activate-chunk.sh ai/chunks/backlog/$(basename "$next_chunk")"
  exit 0
fi

if (( ${#completed_chunks[@]} > 0 )); then
  latest_index=$(( ${#completed_chunks[@]} - 1 ))
  latest_chunk="${completed_chunks[$latest_index]}"
  echo "No active or backlog chunks. Latest completed chunk:"
  echo "  $(basename "$latest_chunk")"
  echo
  echo "Create a new draft or backlog chunk from approved requirements."
  exit 0
fi

echo "No chunks found. Create a draft or backlog chunk from approved requirements."
