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

if [[ $# -lt 1 || $# -gt 2 ]]; then
  echo "usage: $0 <cycle-slug> [version]" >&2
  exit 1
fi

slug="$1"
version="${2:-1}"
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cycle_dir="$root/cycles/$slug"
status_file="$cycle_dir/05-status-v$version.md"

if [[ ! -d "$cycle_dir" ]]; then
  echo "missing cycle: $cycle_dir" >&2
  exit 1
fi

status_of() {
  local path="$1"
  if [[ ! -f "$path" ]]; then
    printf 'missing'
    return
  fi

  if rg -q '^Pending\.$' "$path"; then
    printf 'stub'
    return
  fi

  if ! rg -q '^[[:space:]]*(-[[:space:]]+[A-Za-z0-9]|\d+\.[[:space:]]+[A-Za-z0-9]|[^#[:space:]\-`])' "$path"; then
    printf 'stub'
    return
  fi

  if rg -q '^# [A-Za-z ]+$' "$path" && [[ "$(wc -l < "$path")" -lt 8 ]]; then
    printf 'stub'
    return
  fi

  printf 'written'
}

cat > "$status_file" <<EOF
# Cycle Status

## Summary

- cycle: $slug
- version: v$version
- last updated: $(date -u +"%Y-%m-%d %H:%M UTC")

## Artifact Status

- \`00-user-spec.md\`: $(status_of "$cycle_dir/00-user-spec.md")
- \`10-research-brief.md\`: $(status_of "$cycle_dir/10-research-brief.md")
- \`20-architecture-brief.md\`: $(status_of "$cycle_dir/20-architecture-brief.md")
- \`30-outline.md\`: $(status_of "$cycle_dir/30-outline.md")
- \`40-draft-v$version.md\`: $(status_of "$cycle_dir/40-draft-v$version.md")
- \`50-reviews-v$version/security.md\`: $(status_of "$cycle_dir/50-reviews-v$version/security.md")
- \`50-reviews-v$version/software.md\`: $(status_of "$cycle_dir/50-reviews-v$version/software.md")
- \`50-reviews-v$version/architecture.md\`: $(status_of "$cycle_dir/50-reviews-v$version/architecture.md")
- \`50-reviews-v$version/ietf-senior.md\`: $(status_of "$cycle_dir/50-reviews-v$version/ietf-senior.md")
- \`55-review-synthesis-v$version.md\`: $(status_of "$cycle_dir/55-review-synthesis-v$version.md")
- \`60-revision-plan-v$version.md\`: $(status_of "$cycle_dir/60-revision-plan-v$version.md")

## Notes

- written means the artifact contains substantive content.
- stub means the file exists but still appears to be a placeholder.
- missing means the expected file has not been created.
EOF

echo "$status_file"
