#!/usr/bin/env bash
set -euo pipefail
#
# prdy-status.sh — Quick PRD health check (one-liner output)
#
# Usage:
#   prdy-status.sh [--project <path>] [--format short|json]
#
# Exit codes:
#   0 = PRD ready (all required sections present)
#   1 = PRD incomplete
#   2 = PRD missing

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/_lib.sh"

# ─── Parse arguments ─────────────────────────────────────────────────────────

PROJECT="."
FORMAT="short"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --project) PROJECT="$2"; shift 2 ;;
    --format)  FORMAT="$2"; shift 2 ;;
    -h|--help)
      cat <<'USAGE'
prdy-status.sh — Quick PRD health check

Usage: prdy-status.sh [--project <path>] [--format short|json]

Options:
  --project <path>  Project directory (default: CWD)
  --format <f>      Output format: short (default) or json

Exit codes:
  0 = PRD ready (all required sections present)
  1 = PRD incomplete
  2 = PRD missing
USAGE
      exit 0
      ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

PROJECT="${PROJECT/#\~/$HOME}"

# ─── Status check ────────────────────────────────────────────────────────────

PRD_PATH="$(find_prd "$PROJECT")"

if [[ -z "$PRD_PATH" ]]; then
  if [[ "$FORMAT" == "json" ]]; then
    echo '{"status":"missing"}'
  else
    echo "PRD: missing"
  fi
  exit 2
fi

# Count present sections using the shared manifest
PRD_CONTENT="$(cat "$PRD_PATH")"
total=${#PRDY_REQUIRED_SECTIONS[@]}
present=0

for entry in "${PRDY_REQUIRED_SECTIONS[@]}"; do
  pattern="${entry#*|}"
  if echo "$PRD_CONTENT" | grep -qiE "$pattern"; then
    present=$((present + 1))
  fi
done

# Count additional metrics
fr_count=$(echo "$PRD_CONTENT" | grep -cE '^\- FR-[0-9]+:|^FR-[0-9]+:' || true)
us_count=$(echo "$PRD_CONTENT" | grep -cE '^#{1,4} US-[0-9]+' || true)
assumptions=$(echo "$PRD_CONTENT" | grep -c 'ASSUMPTION:' || true)

if (( present == total )); then
  status="ready"
  exit_code=0
else
  status="incomplete"
  exit_code=1
fi

if [[ "$FORMAT" == "json" ]]; then
  printf '{"status":"%s","sections":%d,"total":%d,"frs":%d,"stories":%d,"assumptions":%d}\n' \
    "$status" "$present" "$total" "$fr_count" "$us_count" "$assumptions"
else
  echo "PRD: $status ($present/$total sections, ${fr_count} FRs, ${us_count} stories, $assumptions assumptions)"
fi

exit "$exit_code"
