#!/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"
review_dir="$cycle_dir/50-reviews-v$version"
status_file="$cycle_dir/05-status-v$version.md"

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

draft_file="$cycle_dir/40-draft-v$version.md"
review_synthesis="$cycle_dir/55-review-synthesis-v$version.md"
revision_plan="$cycle_dir/60-revision-plan-v$version.md"

if [[ ! -f "$draft_file" ]]; then
  cp "$root/templates/40-draft.md" "$draft_file"
fi

if [[ ! -f "$status_file" ]]; then
  cp "$root/templates/05-status.md" "$status_file"
fi

if [[ ! -d "$review_dir" ]]; then
  mkdir -p "$review_dir"
  cp "$root/templates/50-review-security.md" "$review_dir/security.md"
  cp "$root/templates/50-review-software.md" "$review_dir/software.md"
  cp "$root/templates/50-review-architecture.md" "$review_dir/architecture.md"
  cp "$root/templates/50-review-ietf-senior.md" "$review_dir/ietf-senior.md"
fi

if [[ ! -f "$review_synthesis" ]]; then
  cp "$root/templates/55-review-synthesis.md" "$review_synthesis"
fi

if [[ ! -f "$revision_plan" ]]; then
  cp "$root/templates/60-revision-plan.md" "$revision_plan"
fi

cat <<EOF
Cycle: $slug
Version: v$version

Run order:
1. researcher -> $cycle_dir/10-research-brief.md
2. architect -> $cycle_dir/20-architecture-brief.md and $cycle_dir/30-outline.md
3. author -> $draft_file
4. security-reviewer -> $review_dir/security.md
5. software-reviewer -> $review_dir/software.md
6. architecture-reviewer -> $review_dir/architecture.md
7. ietf-senior-reviewer -> $review_dir/ietf-senior.md
8. review-lead -> $review_synthesis and $revision_plan

Core inputs:
- $status_file
- $cycle_dir/00-user-spec.md
- $cycle_dir/10-research-brief.md
- $cycle_dir/20-architecture-brief.md
- $cycle_dir/30-outline.md
- $draft_file
EOF
