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

usage() {
  cat <<'EOF' >&2
Usage: ai/commands/requirements-state.sh [path-to-requirements-file]

Reports read-only requirements lifecycle state. Without a path, reports active requirements files.
Paths must stay inside ai/requirements/{drafts,active,approved,completed}.
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
}

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

validate_requirements_path() {
  local file_path="$1"
  local root="$2"
  local requirements_root="$root/ai/requirements"
  local real_path real_root

  [[ -f "$file_path" ]] || {
    echo "Requirements file does not exist: $file_path" >&2
    return 1
  }

  real_path="$(cd "$(dirname "$file_path")" && pwd)/$(basename "$file_path")"
  real_root="$(cd "$requirements_root" && pwd)"

  case "$real_path" in
    "$real_root"/drafts/requirements-[0-9]*-*.md | "$real_root"/active/requirements-[0-9]*-*.md | "$real_root"/approved/requirements-[0-9]*-*.md | "$real_root"/completed/requirements-[0-9]*-*.md)
      printf '%s\n' "$real_path"
      ;;
    *)
      echo "Requirements path must be inside ai/requirements lifecycle folders: $file_path" >&2
      return 1
      ;;
  esac
}

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"
}

review_verdict() {
  local file="$1"
  local review
  review="$(section "$file" "Requirements Review")"
  if [[ -z "$review" ]]; then
    echo "none"
    return
  fi
  printf '%s\n' "$review" | awk '
    tolower($0) ~ /^[[:space:]-]*verdict[[:space:]]*:/ {
      value = $0
      sub(/^[^:]*:[[:space:]]*/, "", value)
      gsub(/`/, "", value)
      print toupper(value)
      found = 1
      exit
    }
    END { if (!found) print "present" }
  '
}

review_blockers() {
  local file="$1"
  local review
  review="$(section "$file" "Requirements Review")"
  if [[ -z "$review" ]]; then
    echo "(no Requirements Review found)"
    return
  fi
  printf '%s\n' "$review" | awk '
    tolower($0) ~ /^[[:space:]-]*blockers[[:space:]]*:/ {
      value = $0
      sub(/^[^:]*:[[:space:]]*/, "", value)
      print value
      found = 1
      exit
    }
    END { if (!found) print "(no blockers field found)" }
  '
}

latest_pass_heading() {
  local file="$1"
  awk '
    $0 == "## Pass History" { in_history = 1; next }
    in_history && /^## / { exit }
    in_history && /^### (Requirements Intake|Requirements Review|Chunk Planning) Pass [0-9]+/ { latest = $0 }
    END { print latest }
  ' "$file"
}

gate_blockers() {
  local file="$1"
  local status verdict raw user_workflows functional acceptance out_of_scope risks
  local blockers=()

  status="$(metadata_value "$file" "Status")"
  verdict="$(review_verdict "$file")"
  raw="$(section "$file" "Raw Idea")"
  user_workflows="$(section "$file" "User Workflows")"
  functional="$(section "$file" "Functional Requirements")"
  acceptance="$(section "$file" "Acceptance Criteria")"
  out_of_scope="$(section "$file" "Out Of Scope")"
  risks="$(section "$file" "Risks")"

  [[ -n "$raw" ]] || blockers+=("Raw Idea is missing")
  [[ -n "$user_workflows" ]] || blockers+=("User Workflows are missing")
  [[ -n "$functional" ]] || blockers+=("Functional Requirements are missing")
  [[ -n "$acceptance" ]] || blockers+=("Acceptance Criteria are missing")
  [[ -n "$out_of_scope" ]] || blockers+=("Out Of Scope is missing")
  [[ -n "$risks" ]] || blockers+=("Risks are missing")

  if [[ "$status" == "Approved" && "$verdict" != PASS* ]]; then
    blockers+=("Approved requirements must have Requirements Review PASS")
  fi

  if (( ${#blockers[@]} == 0 )); then
    echo "None"
  else
    printf '%s\n' "${blockers[@]}"
  fi
}

print_file_report() {
  local file="$1"
  local root="$2"
  local rel status owner created approved depends validation verdict blockers latest_pass chunk_plan gates

  rel="${file#"$root"/}"
  status="$(metadata_value "$file" "Status")"
  owner="$(metadata_value "$file" "Owner Role")"
  created="$(metadata_value "$file" "Created")"
  approved="$(metadata_value "$file" "Approved")"
  depends="$(metadata_value "$file" "Depends On")"
  validation="$(metadata_value "$file" "Validation")"
  verdict="$(review_verdict "$file")"
  blockers="$(review_blockers "$file")"
  latest_pass="$(latest_pass_heading "$file")"
  chunk_plan="$(section "$file" "Chunk Plan")"
  gates="$(gate_blockers "$file")"

  echo "Requirements State"
  echo
  echo "File: $rel"
  echo "Metadata:"
  echo "  Status: ${status:-"(missing)"}"
  echo "  Owner Role: ${owner:-"(missing)"}"
  echo "  Created: ${created:-"(missing)"}"
  echo "  Approved: ${approved:-"(empty)"}"
  echo "  Depends On: ${depends:-"(empty)"}"
  echo "  Validation: ${validation:-"(empty)"}"
  echo
  echo "Requirements Review verdict: $verdict"
  echo "Requirements Review blockers: $blockers"
  echo "Latest pass: ${latest_pass:-"(no pass history found)"}"
  if [[ -n "$chunk_plan" ]]; then
    echo "Chunk plan: present"
  else
    echo "Chunk plan: missing"
  fi
  echo
  echo "Gate blockers:"
  if [[ "$gates" == "None" ]]; then
    echo "  - none"
  else
    printf '%s\n' "$gates" | sed 's/^/  - /'
  fi
}

root="$(repo_root)"

if [[ $# -gt 1 ]]; then
  usage
  exit 2
fi

if [[ $# -eq 1 ]]; then
  target="$(validate_requirements_path "$(absolute_path "$1" "$root")" "$root")"
  print_file_report "$target" "$root"
  exit 0
fi

shopt -s nullglob
active_files=("$root"/ai/requirements/active/requirements-[0-9]*-*.md)
shopt -u nullglob

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

echo "Requirements State"
echo
echo "Active requirements count: ${#active_files[@]}"
if (( ${#active_files[@]} == 0 )); then
  echo "(no active requirements)"
  exit 1
fi

for file in "${active_files[@]}"; do
  echo
  print_file_report "$file" "$root"
done
