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

if [[ "${RUNTIME_ALLOW_LEGACY_LIFECYCLE_SHELL:-false}" != "true" ]]; then
  cat >&2 <<'EOF'
activate-chunk.sh is retired for normal workflow lifecycle mutation.

Do not use this shell helper as a normal activation path. It directly mutates
chunk lifecycle files and is retained only for explicit severe recovery with:

  RUNTIME_ALLOW_LEGACY_LIFECYCLE_SHELL=true ai/commands/activate-chunk.sh <chunk>

Normal workflow must create/transition work through the Runtime-owned chunk
planning/executor path for the current package.
EOF
  exit 2
fi

if [[ $# -ne 1 ]]; then
  echo "Usage: ai/commands/activate-chunk.sh <path-to-draft-or-backlog-chunk>" >&2
  exit 2
fi

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
}

absolute_path() {
  local input_path="$1"
  local root="$2"
  case "$input_path" in
    /*) echo "$input_path" ;;
    *) echo "$root/$input_path" ;;
  esac
}

update_status() {
  local chunk_path="$1"
  local tmp_file
  tmp_file="$(mktemp)"

  awk '
    BEGIN { in_meta = 0; seen_status = 0 }
    NR == 1 && $0 == "---" { in_meta = 1; print; next }
    in_meta && $0 == "---" {
      if (!seen_status) {
        print "Status: Active"
      }
      in_meta = 0
      print
      next
    }
    in_meta && $0 ~ /^Status:/ {
      print "Status: Active"
      seen_status = 1
      next
    }
    { print }
  ' "$chunk_path" > "$tmp_file"

  mv "$tmp_file" "$chunk_path"
}

root="$(repo_root)"
input_path="$1"
chunk_path="$(absolute_path "$input_path" "$root")"
drafts_dir="$root/ai/chunks/drafts"
backlog_dir="$root/ai/chunks/backlog"
active_dir="$root/ai/chunks/active"

if [[ ! -f "$chunk_path" ]]; then
  echo "Chunk file does not exist: $input_path" >&2
  exit 1
fi

chunk_dir="$(cd "$(dirname "$chunk_path")" && pwd)"
if [[ "$chunk_dir" != "$drafts_dir" && "$chunk_dir" != "$backlog_dir" ]]; then
  echo "Chunk file must be inside ai/chunks/drafts or ai/chunks/backlog: $input_path" >&2
  exit 1
fi

shopt -s nullglob
active_files=("$active_dir"/chunk-[0-9]*-*.md)
shopt -u nullglob

if (( ${#active_files[@]} > 0 )); then
  echo "An active chunk already exists: ${active_files[0]}" >&2
  exit 1
fi

filename="$(basename "$chunk_path")"
destination="$active_dir/$filename"

if [[ -e "$destination" ]]; then
  echo "Active chunk already exists: $destination" >&2
  exit 1
fi

update_status "$chunk_path"
mv "$chunk_path" "$destination"

echo "$destination"
