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

usage() {
  cat <<'EOF'
Usage: ai/commands/workflow-summary.sh [--full|--handoff-only]

Prints a concise, copy-pasteable workflow run packet from fixed repository state.

Modes:
  --full          Include longer chunk sections and pass history.
  --handoff-only Print only the current handoff and advisory next commands.
EOF
}

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
}

section() {
  local file="$1"
  local heading="$2"
  awk -v heading="## ${heading}" '
    $0 == heading { in_section = 1; next }
    in_section && /^## / { exit }
    in_section { print }
  ' "$file" | sed -E '/^[[:space:]]*$/d'
}

metadata_value() {
  local file="$1"
  local key="$2"
  awk -v key="$key" '
    /^---[[:space:]]*$/ {
      fence++
      if (fence == 2) exit
      next
    }
    fence == 1 && index($0, key ":") == 1 {
      value = $0
      sub("^[^:]+:[[:space:]]*", "", value)
      print value
      exit
    }
  ' "$file"
}

field_value_from_text() {
  local text="$1"
  local label="$2"
  printf '%s\n' "$text" | awk -F': ' -v label="$label" '$1 == label { print substr($0, length(label) + 3); exit }'
}

first_heading() {
  local file="$1"
  awk '/^# / { sub(/^# /, ""); print; exit }' "$file"
}

title_from_chunk_filename() {
  local path="$1"
  local base slug
  base="$(basename "$path")"
  slug="$base"
  slug="${slug%.md}"
  slug="${slug#chunk-}"
  slug="${slug#*-}"
  printf '%s\n' "$slug" | tr '-' ' '
}

completed_chunk_from_status() {
  local status_output="$1"
  local matches=()
  local line path
  while IFS= read -r line; do
    [[ -n "$line" ]] || continue
    path="${line:3}"
    case "$path" in
      *" -> "*)
        path="${path##* -> }"
        ;;
    esac
    case "$path" in
      ai/chunks/completed/chunk-[0-9]*-*.md)
        matches+=("$path")
        ;;
    esac
  done <<< "$status_output"

  if (( ${#matches[@]} == 1 )); then
    printf '%s\n' "${matches[0]}"
  fi
}

latest_pass_entries() {
  local file="$1"
  local limit="$2"
  awk -v limit="$limit" '
    $0 == "## Pass History" { in_history = 1; next }
    in_history && /^## / { exit }
    in_history && /^### (Developer|QA) Pass [0-9]+/ {
      if (entry != "") {
        entries[++count] = entry
      }
      entry = $0 "\n"
      next
    }
    in_history && entry != "" {
      entry = entry $0 "\n"
    }
    END {
      if (entry != "") entries[++count] = entry
      start = count - limit + 1
      if (start < 1) start = 1
      for (i = start; i <= count; i++) {
        gsub(/\n[[:space:]]*$/, "", entries[i])
        print entries[i]
        if (i < count) print ""
      }
    }
  ' "$file"
}

trim_section() {
  local max_lines="$1"
  awk -v max_lines="$max_lines" '
    NR <= max_lines { print }
    NR == max_lines + 1 { print "..."; exit }
  '
}

validation_notes() {
  awk '
    /^- Validation:/ { in_validation = 1; print; next }
    in_validation && /^- [A-Z]/ { exit }
    in_validation { print }
  '
}

normalize_commit_text() {
  awk '
    {
      for (i = 1; i <= NF; i++) {
        word = $i
        if (word ~ /^[A-Z0-9][A-Z0-9_-]*$/ && length(word) > 1) {
          normalized = word
        } else {
          normalized = tolower(word)
        }
        output = output (i == 1 ? "" : " ") normalized
      }
      print output
    }
  '
}

derive_commit_message() {
  local title="$1"
  local fallback="$2"
  local message verb rest
  message="$title"
  if [[ -z "$message" ]]; then
    message="$fallback"
  fi
  message="$(printf '%s\n' "$message" | sed -E 's/^[[:space:]]+|[[:space:]]+$//g')"
  if [[ -z "$message" ]]; then
    message="Update workflow state"
  fi
  case "$message" in
    Add\ * | Update\ * | Fix\ * | Create\ * | Remove\ * | Document\ * | Improve\ * | Commit\ *)
      verb="${message%% *}"
      rest="${message#* }"
      if [[ "$rest" == "$message" ]]; then
        printf '%s\n' "$verb"
      else
        printf '%s %s\n' "$verb" "$(printf '%s\n' "$rest" | normalize_commit_text)"
      fi
      ;;
    *)
      printf 'Add %s\n' "$(printf '%s\n' "$message" | normalize_commit_text)"
      ;;
  esac
}

derive_advisory_commit() {
  local state="$1"
  local title="$2"
  local fallback="$3"
  local completed_chunk completed_title

  if [[ "$state" == "commit_ready" && -z "$title" ]]; then
    completed_chunk="$(completed_chunk_from_status "$git_status")"
    if [[ -n "$completed_chunk" ]]; then
      if [[ -f "$root/$completed_chunk" ]]; then
        completed_title="$(first_heading "$root/$completed_chunk")"
      fi
      if [[ -z "${completed_title:-}" ]]; then
        completed_title="$(title_from_chunk_filename "$completed_chunk")"
      fi
      printf 'git commit -m "%s"\n' "$(derive_commit_message "$completed_title" "")"
      return
    fi

    printf 'manual commit message required - no single completed chunk found in git status\n'
    return
  fi

  printf 'git commit -m "%s"\n' "$(derive_commit_message "$title" "$fallback")"
}

print_code_or_empty() {
  local content="$1"
  local empty_message="$2"
  if [[ -n "$content" ]]; then
    printf '%s\n' "$content"
  else
    printf '%s\n' "$empty_message"
  fi
}

safe_git_add_command() {
  local status_output="$1"
  local paths=()
  local status path
  while IFS= read -r status; do
    [[ -n "$status" ]] || continue
    path="${status:3}"
    [[ -n "$path" ]] || continue
    case "$path" in
      .tmp | .tmp/* | .env | .env.* | */.env | */.env.*)
        continue
        ;;
      *" -> "*)
        path="${path##* -> }"
        ;;
    esac
    paths+=("$path")
  done <<< "$status_output"

  if (( ${#paths[@]} == 0 )); then
    echo "git add <reviewed files>"
    return
  fi

  printf 'git add'
  printf ' %q' "${paths[@]}"
  printf '\n'
}

safe_git_add_file_list() {
  local status_output="$1"
  local paths=()
  local status path
  while IFS= read -r status; do
    [[ -n "$status" ]] || continue
    path="${status:3}"
    [[ -n "$path" ]] || continue
    case "$path" in
      .tmp | .tmp/* | .env | .env.* | */.env | */.env.* | *secret* | *token* | *password*)
        continue
        ;;
      *" -> "*)
        path="${path##* -> }"
        ;;
    esac
    paths+=("$path")
  done <<< "$status_output"

  if (( ${#paths[@]} == 0 )); then
    echo "<reviewed files>"
    return
  fi

  local IFS='|'
  printf '%s\n' "${paths[*]}"
}

untracked_paths() {
  local status_output="$1"
  local line path
  while IFS= read -r line; do
    [[ -n "$line" ]] || continue
    case "$line" in
      "?? "*)
        path="${line#?? }"
        printf '%s\n' "$path"
        ;;
    esac
  done <<< "$status_output"
}

untracked_count() {
  local status_output="$1"
  local paths
  paths="$(untracked_paths "$status_output")"
  if [[ -z "$paths" ]]; then
    echo 0
  else
    printf '%s\n' "$paths" | wc -l | tr -d ' '
  fi
}

handoff_field() {
  local text="$1"
  local label="$2"
  printf '%s\n' "$text" | awk -F': ' -v label="- ${label}" '$1 == label { print substr($0, length(label) + 3); exit }'
}

print_handoff_without_commands() {
  local text="$1"
  printf '%s\n' "$text" | awk '
    /^## Handoff/ { in_handoff = 1 }
    in_handoff && /^- Exact Next Command:/ { next }
    in_handoff && /^- Immediate Next Command:/ { next }
    in_handoff && /^- Post-Approval Command:/ { next }
    in_handoff && /^- Autopilot Continuation:/ { next }
    in_handoff && /^- Advisory Git Commands:/ { next }
    in_handoff && /^- Optional Prompt Review Command:/ { next }
    in_handoff { print }
  '
}

readiness_command_for_state() {
  case "$canonical_state" in
    ready_for_qa)
      echo "ai/commands/workflow-state.sh --ready-for-qa"
      ;;
    qa_passed | ready_to_complete)
      echo "ai/commands/workflow-state.sh --ready-to-complete"
      ;;
    *)
      echo "ai/commands/workflow-state.sh"
      ;;
  esac
}

shell_quote() {
  local value="$1"
  printf "'%s'" "$(printf '%s' "$value" | sed "s/'/'\\\\''/g")"
}

print_suggested_commands() {
  local exact_command="$1"
  local review_command="$2"
  local post_approval_command="${3:-}"
  local autopilot_continuation="${4:-}"
  local readiness_command
  readiness_command="$(readiness_command_for_state)"

  echo "## Suggested Commands"
  echo
  echo "- Readiness gate: $readiness_command"

  if [[ -n "$exact_command" ]]; then
    if [[ "$exact_command" == ai/commands/prompt-synthesize.sh* ]]; then
      echo "- Prompt synthesis: $exact_command"
    elif [[ "$canonical_state" == "ready_to_complete" && "$exact_command" == "ai/commands/workflow-summary.sh" ]]; then
      echo "- Immediate human review: $exact_command"
    elif [[ "$exact_command" == *"complete-chunk.sh"* ]]; then
      echo "- Completion: $exact_command"
    else
      echo "- Next command: $exact_command"
    fi
  fi

  if [[ -n "$review_command" ]]; then
    echo "- Optional prompt review: $review_command"
  fi

  if [[ -n "$post_approval_command" ]]; then
    if [[ "$post_approval_command" == ai/tools/operator-daemon/request-action.sh* ]]; then
      echo "- Trusted daemon completion: $post_approval_command"
    elif [[ "$post_approval_command" == ai/commands/workflow-approve-action.sh* ]]; then
      echo "- Legacy approval fallback: $post_approval_command"
    else
      echo "- Post-approval completion: $post_approval_command"
    fi
  fi

  if [[ -n "$autopilot_continuation" ]]; then
    echo "- Autopilot continuation: $autopilot_continuation"
  fi

  if [[ "$canonical_state" == "ready_to_complete" || "$canonical_state" == "commit_ready" ]]; then
    daemon_files="$(safe_git_add_file_list "$git_status")"
    echo "- Trusted daemon git add: ai/tools/operator-daemon/request-action.sh --action git_add_approved --files $(shell_quote "$daemon_files")"
    echo "- Trusted daemon wait: ai/tools/operator-daemon/wait-result.sh <request-id>"
    if [[ "$advisory_git_commit" != manual\ commit\ message\ required* ]]; then
      commit_message="${advisory_git_commit#git commit -m }"
      commit_message="${commit_message%\"}"
      commit_message="${commit_message#\"}"
      echo "- Trusted daemon git commit: ai/tools/operator-daemon/request-action.sh --action git_commit --message $(shell_quote "$commit_message")"
    else
      echo "- Trusted daemon git commit: choose a reviewed commit message, then run ai/tools/operator-daemon/request-action.sh --action git_commit --message \"<message>\""
    fi
    echo "- Git guidance: use request-action plus wait-result; raw git add/commit, direct run-once, and Codex platform escalation are not the registered-action path."
  fi

  echo "- Note: advisory only; no git, Codex, Telegram, tmux, commit, or app runtime commands were executed."
}

mode="summary"
case "${1:-}" in
  "")
    ;;
  --full)
    mode="full"
    ;;
  --handoff-only)
    mode="handoff"
    ;;
  -h | --help)
    usage
    exit 0
    ;;
  *)
    usage >&2
    exit 2
    ;;
esac

root="$(repo_root)"
workflow_state_output="$("$root/ai/commands/workflow-state.sh" 2>&1 || true)"
orchestrator_next_output="$("$root/ai/commands/orchestrator-next.sh" 2>&1 || true)"
git_status="$(git -C "$root" status --short --untracked-files=all)"
git_diff_stat="$(git -C "$root" diff --stat)"
git_untracked_paths="$(untracked_paths "$git_status")"
git_untracked_count="$(untracked_count "$git_status")"

active_chunk="$(field_value_from_text "$workflow_state_output" "Active chunk")"
canonical_state="$(field_value_from_text "$workflow_state_output" "Canonical state")"
current_phase="$(field_value_from_text "$workflow_state_output" "Current phase")"
latest_pass="$(field_value_from_text "$workflow_state_output" "Latest pass")"
qa_verdict="$(field_value_from_text "$workflow_state_output" "QA verdict")"
recommended_action="$(field_value_from_text "$workflow_state_output" "Recommended next action")"
completion_gate="$(field_value_from_text "$workflow_state_output" "Completion gate")"

active_chunk_path=""
if [[ "$active_chunk" == ai/chunks/active/* && -f "$root/$active_chunk" ]]; then
  active_chunk_path="$root/$active_chunk"
fi

chunk_title=""
chunk_status=""
chunk_validation=""
if [[ -n "$active_chunk_path" ]]; then
  chunk_title="$(first_heading "$active_chunk_path")"
  chunk_status="$(metadata_value "$active_chunk_path" "Status")"
  chunk_validation="$(metadata_value "$active_chunk_path" "Validation")"
fi

advisory_git_add="$(safe_git_add_command "$git_status")"
advisory_git_commit="$(derive_advisory_commit "$canonical_state" "$chunk_title" "$recommended_action")"
handoff_exact_command="$(handoff_field "$orchestrator_next_output" "Exact Next Command")"
handoff_review_command="$(handoff_field "$orchestrator_next_output" "Optional Prompt Review Command")"
handoff_post_approval_command="$(handoff_field "$orchestrator_next_output" "Post-Approval Command")"
handoff_autopilot_continuation="$(handoff_field "$orchestrator_next_output" "Autopilot Continuation")"

if [[ "$mode" == "handoff" ]]; then
  printf '%s\n' "$orchestrator_next_output" | awk '
    /^Recommended Next Action/ { print; next }
    /^Exact Next Command:/ { next }
    /^Immediate Next Command:/ { next }
    /^Post-Approval Command:/ { next }
    /^Autopilot Continuation:/ { next }
    /^Advisory Git Commands:/ { next }
    /^Optional Prompt Review Command:/ { next }
    /^- Exact Next Command:/ { next }
    /^- Immediate Next Command:/ { next }
    /^- Post-Approval Command:/ { next }
    /^- Autopilot Continuation:/ { next }
    /^- Advisory Git Commands:/ { next }
    /^- Optional Prompt Review Command:/ { next }
    { print }
  '
  echo
  print_suggested_commands "$handoff_exact_command" "$handoff_review_command" "$handoff_post_approval_command" "$handoff_autopilot_continuation"
  exit 0
fi

echo "# Workflow Summary"
echo
echo "## State"
echo
echo "- Active Chunk: ${active_chunk:-"(none)"}"
if [[ -n "$chunk_title" ]]; then
  echo "- Chunk Title: $chunk_title"
fi
if [[ -n "$chunk_status" ]]; then
  echo "- Chunk Status: $chunk_status"
fi
echo "- Canonical State: ${canonical_state:-"(unknown)"}"
echo "- Current Phase: ${current_phase:-"(unknown)"}"
echo "- Latest Pass: ${latest_pass:-"(none)"}"
echo "- QA Verdict: ${qa_verdict:-"(none)"}"
echo "- Completion Gate: ${completion_gate:-"(unknown)"}"
echo "- Recommended Next Action: ${recommended_action:-"(unknown)"}"
echo
print_handoff_without_commands "$orchestrator_next_output"

if [[ -n "$active_chunk_path" ]]; then
  execution_notes="$(section "$active_chunk_path" "Execution Notes")"
  acceptance="$(section "$active_chunk_path" "Acceptance Criteria Verification")"
  qa_review="$(section "$active_chunk_path" "QA Review")"
  handoff="$(section "$active_chunk_path" "Handoff")"
  pass_history="$(latest_pass_entries "$active_chunk_path" 2)"

  echo
  echo "## Execution Notes Summary"
  echo
  if [[ "$mode" == "full" ]]; then
    print_code_or_empty "$execution_notes" "(none)"
  else
    printf '%s\n' "$execution_notes" | trim_section 12
  fi

  echo
  echo "## Acceptance Criteria Verification"
  echo
  print_code_or_empty "$acceptance" "(none)"

  echo
  echo "## QA Review"
  echo
  print_code_or_empty "$qa_review" "(none)"

  echo
  echo "## Latest Pass History"
  echo
  if [[ "$mode" == "full" ]]; then
    print_code_or_empty "$(latest_pass_entries "$active_chunk_path" 5)" "(none)"
  else
    print_code_or_empty "$pass_history" "(none)"
  fi

  echo
  echo "## Validation Evidence"
  echo
  if [[ -n "$chunk_validation" ]]; then
    echo "- Metadata Validation: $chunk_validation"
  else
    echo "- Metadata Validation: (none)"
  fi
  if printf '%s\n' "$execution_notes" | grep -q 'workflow-scenarios-test.sh'; then
    echo "- Scenario Harness: referenced in Execution Notes."
  elif [[ "$chunk_validation" == *"workflow-scenarios-test.sh"* ]]; then
    echo "- Scenario Harness: listed in metadata validation."
  else
    echo "- Scenario Harness: not listed for this chunk."
  fi
  notes_validation="$(printf '%s\n' "$execution_notes" | validation_notes)"
  if [[ -n "$notes_validation" ]]; then
    echo "- Notes Validation:"
    printf '%s\n' "$notes_validation" | sed 's/^/  /'
  else
    echo "- Notes Validation: (none found)"
  fi

  if [[ -n "$handoff" && "$mode" == "full" ]]; then
    echo
    echo "## Chunk Handoff"
    echo
    printf '%s\n' "$handoff"
  fi
fi

echo
echo "## Git Status"
echo
if [[ -n "$git_status" ]]; then
  printf '%s\n' "$git_status"
else
  echo "(clean)"
fi

echo
echo "## Git Diff Stat"
echo
if [[ -n "$git_diff_stat" ]]; then
  printf '%s\n' "$git_diff_stat"
else
  if (( git_untracked_count > 0 )); then
    echo "(no tracked diff)"
    echo "Untracked files: $git_untracked_count"
    printf '%s\n' "$git_untracked_paths" | sed 's/^/- /'
  else
    echo "(no diff)"
  fi
fi

echo
print_suggested_commands "$handoff_exact_command" "$handoff_review_command" "$handoff_post_approval_command" "$handoff_autopilot_continuation"
