#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn
# shellcheck disable=SC2016,SC2317
# SC2016: $ARGUMENTS is a Claude Code template placeholder written literally to .md files
# SC2317: Functions defined after arg-parsing case (which contains exit 0 in --help)
#         appear unreachable to ShellCheck but are always reached in normal execution
# =============================================================================
# DEPRECATED: Use generate-runtime-config.sh instead (t1665.4)
# This script is kept for one release cycle as a fallback.
# .agents/scripts/setup/modules/config.sh will use generate-runtime-config.sh when available.
# =============================================================================
# Generate Claude Code Commands from Agent Files
# =============================================================================
# Creates slash commands in Claude Code from the same source as OpenCode commands.
#
# Source: ~/.aidevops/agents/scripts/commands/*.md (primary, auto-discovered)
#         + hardcoded commands not in scripts/commands/ (parity with OpenCode)
# Target: ~/.claude/commands/
#
# Claude Code format:
#   - Files in ~/.claude/commands/name.md become /name
#   - YAML frontmatter: description (shown in / menu), allowed-tools (optional)
#   - $ARGUMENTS placeholder for user input after the command
#   - No agent/mode/subtask fields (OpenCode-specific, stripped during generation)
#
# Usage:
#   bash generate-claude-commands.sh [--dry-run] [--clean]
#
# Options:
#   --dry-run   Show what would be generated without writing files
#   --clean     Remove all generated commands before regenerating
# =============================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" || exit
source "${SCRIPT_DIR}/shared-constants.sh"

set -euo pipefail

CLAUDE_COMMAND_DIR="$HOME/.claude/commands"
COMMANDS_SOURCE_DIR="$HOME/.aidevops/agents/scripts/commands"

# Parse arguments
DRY_RUN=false
CLEAN=false
for arg in "$@"; do
	case "$arg" in
	--dry-run) DRY_RUN=true ;;
	--clean) CLEAN=true ;;
	--help | -h)
		echo "Usage: generate-claude-commands.sh [--dry-run] [--clean]"
		echo ""
		echo "Generate Claude Code slash commands from aidevops agent command files."
		echo ""
		echo "Options:"
		echo "  --dry-run   Show what would be generated without writing files"
		echo "  --clean     Remove all generated commands before regenerating"
		exit 0
		;;
	*)
		echo "Unknown option: $arg"
		exit 1
		;;
	esac
done

echo -e "${BLUE}Generating Claude Code commands...${NC}"

# Ensure command directory exists
[[ "$DRY_RUN" == "true" ]] || mkdir -p "$CLAUDE_COMMAND_DIR"

command_count=0

# =============================================================================
# HELPER: Clean existing commands
# =============================================================================

clean_commands() {
	[[ "$CLEAN" == "true" && "$DRY_RUN" == "false" ]] || return 0

	echo -e "  ${YELLOW}Cleaning existing commands...${NC}"
	local clean_count=0
	local f
	for f in "$CLAUDE_COMMAND_DIR"/*.md; do
		[[ -f "$f" ]] || continue
		[[ "$(basename "$f")" == "AGENTS.md" ]] && continue
		rm "$f"
		((++clean_count))
	done
	echo -e "  ${GREEN}Removed $clean_count commands${NC}"
	return 0
}

# =============================================================================
# HELPER: Transform frontmatter for Claude Code
# =============================================================================
# Strips OpenCode-specific fields (agent, mode, subtask) from YAML frontmatter.
# Keeps: description. Adds: generator marker.
# =============================================================================

transform_command_file() {
	local source_file="$1"
	local target_file="$2"
	local cmd_name="$3"

	local first_line
	first_line=$(head -1 "$source_file")

	# No frontmatter — wrap with minimal frontmatter
	if [[ "$first_line" != "---" ]]; then
		{
			echo "---"
			echo "# Generated by generate-claude-commands.sh — do not edit manually"
			echo "description: $cmd_name command"
			echo "---"
			echo ""
			cat "$source_file"
		} >"$target_file"
		return 0
	fi

	# Extract description from frontmatter (between first and second ---)
	local description
	description=$(awk '/^---$/{n++; next} n==1 && /^description:/{sub(/^description: */, ""); print; exit}' "$source_file")
	[[ -n "$description" ]] || description="$cmd_name command"

	# Write new frontmatter header, then append body after second ---
	{
		echo "---"
		echo "# Generated by generate-claude-commands.sh — do not edit manually"
		echo "description: $description"
		echo "---"
	} >"$target_file"
	awk 'BEGIN{n=0} /^---$/{n++; next} n>=2{print}' "$source_file" >>"$target_file"
	return 0
}

# =============================================================================
# HELPER: Write a hardcoded command
# =============================================================================

write_command() {
	local cmd_name="$1"
	local description="$2"
	local body="$3"

	if [[ "$DRY_RUN" == "true" ]]; then
		echo -e "  ${BLUE}[dry-run]${NC} Would create /$cmd_name — $description"
		((++command_count))
		return 0
	fi

	{
		echo "---"
		echo "# Generated by generate-claude-commands.sh — do not edit manually"
		echo "description: $description"
		echo "---"
		echo ""
		echo "$body"
	} >"$CLAUDE_COMMAND_DIR/$cmd_name.md" || return 1

	((++command_count))
	echo -e "  ${GREEN}✓${NC} Created /$cmd_name"
	return 0
}

# =============================================================================
# HELPER: Conditionally generate a hardcoded command
# =============================================================================
# Skips if the command was already created in Phase 1 (auto-discovered).
# =============================================================================

maybe_write_command() {
	local cmd_name="$1"
	local description="$2"
	local body="$3"

	# Skip if already generated in Phase 1
	if [[ "$DRY_RUN" == "true" ]]; then
		[[ ! -f "$COMMANDS_SOURCE_DIR/$cmd_name.md" ]] || return 0
	else
		[[ ! -f "$CLAUDE_COMMAND_DIR/$cmd_name.md" ]] || return 0
	fi

	write_command "$cmd_name" "$description" "$body" || return 1
	return 0
}

# =============================================================================
# PHASE 1: Auto-discover commands from scripts/commands/*.md
# =============================================================================

discover_commands() {
	echo -e "${BLUE}Phase 1: Auto-discovering from scripts/commands/...${NC}"

	if [[ ! -d "$COMMANDS_SOURCE_DIR" ]]; then
		echo -e "  ${YELLOW}⚠${NC} Source directory not found: $COMMANDS_SOURCE_DIR"
		echo -e "  ${YELLOW}⚠${NC} Run setup.sh first to deploy agents"
		return 0
	fi

	local cmd_file cmd_name desc
	for cmd_file in "$COMMANDS_SOURCE_DIR"/*.md; do
		[[ -f "$cmd_file" ]] || continue
		cmd_name=$(basename "$cmd_file" .md)
		[[ "$cmd_name" == "SKILL" ]] && continue

		if [[ "$DRY_RUN" == "true" ]]; then
			desc=$(grep -E '^description:' "$cmd_file" | head -1 | sed 's/^description: *//' || echo "$cmd_name")
			echo -e "  ${BLUE}[dry-run]${NC} Would create /$cmd_name — $desc"
			((++command_count))
			continue
		fi

		transform_command_file "$cmd_file" "$CLAUDE_COMMAND_DIR/$cmd_name.md" "$cmd_name"
		((++command_count))
		echo -e "  ${GREEN}✓${NC} /$cmd_name"
	done
	return 0
}

# =============================================================================
# PHASE 2: Hardcoded commands (parity with generate-opencode-commands.sh)
# =============================================================================
# These commands are defined inline and don't have corresponding files in
# scripts/commands/. We generate them here for Claude Code parity.
# Each call to maybe_write_command skips if already created in Phase 1.
#
# Decomposed into domain-specific helpers to keep each function under 100 lines.
# =============================================================================

# -----------------------------------------------------------------------------
# Workflow commands: agent-review, preflight, postflight, review-issue-pr,
#                    release, version-bump, changelog
# -----------------------------------------------------------------------------
_generate_workflow_commands() {
	maybe_write_command "agent-review" \
		"Systematic review and improvement of agent instructions" \
		'Read ~/.aidevops/agents/tools/build-agent/agent-review.md and follow its instructions.

Review the agent file(s) specified: $ARGUMENTS

If no specific file is provided, review the agents used in this session and propose improvements based on:
1. Any corrections the user made
2. Any commands or paths that failed
3. Instruction count (target <50 for main, <100 for subagents)
4. Universal applicability (>80% of tasks)
5. Duplicate detection across agents

Follow the improvement proposal format from the agent-review instructions.' || return 1

	maybe_write_command "preflight" \
		"Run quality checks before version bump and release" \
		'Read ~/.aidevops/agents/workflows/preflight.md and follow its instructions.

Run preflight checks for: $ARGUMENTS

This includes:
1. Code quality checks (ShellCheck, SonarCloud, secrets scan)
2. Markdown formatting validation
3. Version consistency verification
4. Git status check (clean working tree)' || return 1

	maybe_write_command "postflight" \
		"Check code audit feedback on latest push (branch or PR)" \
		'Check code audit tool feedback on the latest push.

Target: $ARGUMENTS

**Auto-detection:**
1. If in a linked worktree with open PR -> check that PR'\''s feedback
2. If in a linked worktree without PR -> check ref CI status
3. If on main -> check latest commit'\''s CI/audit status
4. If no git context or ambiguous -> ask user which branch/PR to check

**Checks performed:**
1. GitHub Actions workflow status (pass/fail/pending)
2. CodeRabbit comments and suggestions
3. Codacy analysis results
4. SonarCloud quality gate status
5. Any blocking issues that need resolution

Report findings and recommend next actions (fix issues, merge, etc.)' || return 1

	maybe_write_command "review-issue-pr" \
		"Review external issue or PR - validate problem and evaluate solution" \
		'Read ~/.aidevops/agents/workflows/review-issue-pr.md and follow its instructions.

Review this issue or PR: $ARGUMENTS

**Usage:**
- `/review-issue-pr 123` - Review issue or PR by number
- `/review-issue-pr https://github.com/owner/repo/issues/123` - Review by URL
- `/review-issue-pr https://github.com/owner/repo/pull/456` - Review PR by URL

**Core questions to answer:**
1. Is the issue real? (reproducible, not duplicate, actually a bug)
2. Is this the best solution? (simplest approach, fixes root cause)
3. Is the scope appropriate? (minimal changes, no scope creep)' || return 1

	maybe_write_command "release" \
		"Full release workflow with version bump, tag, and GitHub release" \
		'Execute a release for the current repository.

Release type: $ARGUMENTS (valid: major, minor, patch)

**Steps:**
1. Run `git log v$(cat VERSION 2>/dev/null || echo "0.0.0")..HEAD --oneline` to see commits since last release
2. If no release type provided, determine it from commits:
   - Any `feat:` or new feature -> minor
   - Only `fix:`, `docs:`, `chore:`, `perf:`, `refactor:` -> patch
   - Any `BREAKING CHANGE:` or `!` -> major
3. Run the single release command:
   ```bash
   .agents/scripts/version-manager.sh release [type] --skip-preflight --force
   ```
4. Report the result with the GitHub release URL

**CRITICAL**: Use only the single command above - it handles everything atomically.' || return 1

	maybe_write_command "version-bump" \
		"Bump project version (major, minor, or patch)" \
		'Read ~/.aidevops/agents/workflows/version-bump.md and follow its instructions.

Bump type: $ARGUMENTS

Valid types: major, minor, patch

This updates:
1. VERSION file
2. package.json (if exists)
3. Other version references as configured' || return 1

	maybe_write_command "changelog" \
		"Update CHANGELOG.md following Keep a Changelog format" \
		'Read ~/.aidevops/agents/workflows/changelog.md and follow its instructions.

Action: $ARGUMENTS

This maintains CHANGELOG.md with:
- Unreleased section for pending changes
- Version sections with dates
- Categories: Added, Changed, Deprecated, Removed, Fixed, Security' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# Code quality commands: linters-local, code-audit-remote, code-standards,
#                        code-simplifier
# -----------------------------------------------------------------------------
_generate_quality_commands() {
	maybe_write_command "linters-local" \
		"Run local linting tools (ShellCheck, secretlint, pattern checks)" \
		'Run the local linters script:

```bash
~/.aidevops/agents/scripts/linters-local.sh $ARGUMENTS
```

This runs fast, offline checks:
1. ShellCheck for shell scripts
2. Secretlint for exposed secrets
3. Pattern validation (return statements, positional parameters)
4. Markdown formatting checks

For remote auditing (CodeRabbit, Codacy, SonarCloud), use /code-audit-remote' || return 1

	maybe_write_command "code-audit-remote" \
		"Run remote code auditing (CodeRabbit, Codacy, SonarCloud)" \
		'Read ~/.aidevops/agents/workflows/code-audit-remote.md and follow its instructions.

Audit target: $ARGUMENTS

This calls external quality services:
1. CodeRabbit - AI-powered code review
2. Codacy - Code quality analysis
3. SonarCloud - Security and maintainability

For local linting (fast, offline), use /linters-local first' || return 1

	maybe_write_command "code-standards" \
		"Check code against documented quality standards" \
		'Read ~/.aidevops/agents/tools/code-review/code-standards.md and follow its instructions.

Check target: $ARGUMENTS

This validates against our documented standards:
- S7682: Explicit return statements
- S7679: Positional parameters assigned to locals
- S1192: Constants for repeated strings
- S1481: No unused variables
- ShellCheck: Zero violations' || return 1

	maybe_write_command "code-simplifier" \
		"Simplify and refine code for clarity, consistency, and maintainability" \
		'Read ~/.aidevops/agents/tools/code-review/code-simplifier.md and follow its instructions.

Target: $ARGUMENTS

**Usage:**
- `/code-simplifier` — Simplify recently modified code
- `/code-simplifier src/` — Simplify code in specific directory
- `/code-simplifier --all` — Review entire codebase (use sparingly)

**Key Principles:**
- Preserve exact functionality
- Clarity over brevity
- Apply project standards' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# Branch commands: feature, bugfix, hotfix
# -----------------------------------------------------------------------------
_generate_branch_commands() {
	maybe_write_command "feature" \
		"Create and develop a feature in a linked worktree" \
		'Read ~/.aidevops/agents/workflows/branch/feature.md and follow its instructions.

Feature: $ARGUMENTS

This will:
1. Create safe linked worktree for the feature from main
2. Set up development environment
3. Guide feature implementation' || return 1

	maybe_write_command "bugfix" \
		"Create and resolve a bugfix in a linked worktree" \
		'Read ~/.aidevops/agents/workflows/branch/bugfix.md and follow its instructions.

Bug: $ARGUMENTS

This will:
1. Create safe linked worktree for the bugfix
2. Guide bug investigation
3. Implement and test fix' || return 1

	maybe_write_command "hotfix" \
		"Urgent hotfix for critical production issues" \
		'Read ~/.aidevops/agents/workflows/branch/hotfix.md and follow its instructions.

Issue: $ARGUMENTS

This will:
1. Create safe linked worktree for the hotfix from production
2. Implement minimal fix
3. Fast-track to release' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# Utility commands: list-keys, log-time-spent, context, create-pr, pr
# -----------------------------------------------------------------------------
_generate_utility_commands() {
	maybe_write_command "list-keys" \
		"List all API keys available in session with their storage locations" \
		'Run the list-keys helper script and format the output as a markdown table:

```bash
~/.aidevops/agents/scripts/list-keys-helper.sh --json $ARGUMENTS
```

Parse the JSON output and present as markdown tables grouped by source.
Security: Key values are NEVER displayed.' || return 1

	maybe_write_command "log-time-spent" \
		"Log time spent on a task in TODO.md" \
		'Log time spent on a task.

Arguments: $ARGUMENTS

**Format:** `/log-time-spent [task-id-or-description] [duration]`

**Examples:**
- `/log-time-spent "Add user dashboard" 2h30m`
- `/log-time-spent t001 45m`
- `/log-time-spent` (prompts for task and duration)

**Duration formats:** 2h, 30m, 2h30m, 1.5h' || return 1

	maybe_write_command "context" \
		"Build token-efficient AI context for complex tasks" \
		'Read ~/.aidevops/agents/tools/context/context-builder.md and follow its instructions.

Context request: $ARGUMENTS

This generates optimized context for AI assistants including:
1. Relevant code snippets
2. Architecture overview
3. Dependencies and relationships' || return 1

	maybe_write_command "create-pr" \
		"Create PR from current branch with title and description" \
		'Create a pull request from the current branch.

Additional context: $ARGUMENTS

**Steps:**
1. Check current worktree ref (must not be main/master)
2. Check for uncommitted changes (warn if present)
3. Push current worktree ref to remote if not already pushed
4. Generate PR title from ref name
5. Generate PR description from commit messages and changed files
6. Create PR using `gh pr create`
7. Return PR URL' || return 1

	maybe_write_command "pr" \
		"Alias for /create-pr - Create PR from current branch" \
		'This is an alias for /create-pr. Creating PR from current branch.

Context: $ARGUMENTS

Run /create-pr with the same arguments.' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# Planning commands: create-prd, generate-tasks, plan-status
# -----------------------------------------------------------------------------
_generate_planning_commands() {
	maybe_write_command "create-prd" \
		"Generate a Product Requirements Document for a feature" \
		'Read ~/.aidevops/agents/workflows/plans.md and follow its PRD generation instructions.

Feature to document: $ARGUMENTS

**Workflow:**
1. Ask 3-5 clarifying questions with numbered options (1A, 2B format)
2. Generate PRD using template
3. Save to todo/tasks/prd-{feature-slug}.md
4. Offer to generate tasks with /generate-tasks' || return 1

	maybe_write_command "generate-tasks" \
		"Generate implementation tasks from a PRD" \
		'Read ~/.aidevops/agents/workflows/plans.md and follow its task generation instructions.

PRD or feature: $ARGUMENTS

**Workflow:**
1. If PRD file provided, read it
2. If feature name provided, look for todo/tasks/prd-{name}.md
3. Generate parent tasks (Phase 1) and present to user
4. Wait for user to say "Go"
5. Generate sub-tasks (Phase 2)
6. Save to todo/tasks/tasks-{feature-slug}.md' || return 1

	maybe_write_command "plan-status" \
		"Show active plans and TODO.md status" \
		'Read TODO.md and todo/PLANS.md to show current planning status.

Filter: $ARGUMENTS (optional: "in-progress", "backlog", plan name)

Show:
1. In-progress tasks
2. Top backlog items
3. Active plans with progress
4. Offer to work on a specific task' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# SEO keyword research commands: keyword-research, autocomplete-research,
#                                 keyword-research-extended, webmaster-keywords
# -----------------------------------------------------------------------------
_generate_seo_keyword_commands() {
	maybe_write_command "keyword-research" \
		"Keyword research with seed keyword expansion" \
		'Read ~/.aidevops/agents/seo/keyword-research.md and follow its instructions.

Keywords to research: $ARGUMENTS

**Options from arguments:**
- `--provider dataforseo|serper|both`
- `--locale us-en|uk-en|etc`
- `--limit N`
- `--csv` - Export to ~/Downloads/' || return 1

	maybe_write_command "autocomplete-research" \
		"Google autocomplete long-tail keyword expansion" \
		'Read ~/.aidevops/agents/seo/keyword-research.md and follow its instructions.

Seed keyword for autocomplete: $ARGUMENTS

This uses DataForSEO or Serper autocomplete API to discover
question-based and long-tail keywords.' || return 1

	maybe_write_command "keyword-research-extended" \
		"Full SERP analysis with weakness detection and KeywordScore" \
		'Read ~/.aidevops/agents/seo/keyword-research.md and follow its instructions.

Research target: $ARGUMENTS

**Modes:**
- Default: Full SERP analysis on keywords
- `--domain example.com` - Keywords associated with domain'\''s niche
- `--competitor example.com` - Exact keywords competitor ranks for
- `--gap yourdomain.com,competitor.com` - Keywords they have that you don'\''t' || return 1

	maybe_write_command "webmaster-keywords" \
		"Keywords from GSC + Bing for your verified sites" \
		'Read ~/.aidevops/agents/seo/keyword-research.md and follow its instructions.

Site URL: $ARGUMENTS

Fetches keywords from Google Search Console and Bing Webmaster Tools,
combines and deduplicates results, enriches with volume/difficulty data.' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# SEO AI-search commands: seo-fanout, seo-geo, seo-sro,
#                         seo-hallucination-defense, seo-agent-discovery,
#                         seo-ai-readiness, seo-ai-baseline
# -----------------------------------------------------------------------------
_generate_seo_ai_commands() {
	maybe_write_command "seo-fanout" \
		"Run thematic query fan-out research for AI search coverage" \
		'Read ~/.aidevops/agents/seo/query-fanout-research.md and follow its instructions.

Target: $ARGUMENTS

Produce thematic branches, prioritized sub-queries, a page coverage matrix, and a remediation backlog.' || return 1

	maybe_write_command "seo-geo" \
		"Run GEO strategy workflow for AI search visibility" \
		'Read ~/.aidevops/agents/seo/geo-strategy.md and follow its instructions.

Target: $ARGUMENTS

Deliverables: decision-criteria matrix, page-level coverage map, and prioritized retrieval-first improvements.' || return 1

	maybe_write_command "seo-sro" \
		"Run Selection Rate Optimization workflow for grounding snippets" \
		'Read ~/.aidevops/agents/seo/sro-grounding.md and follow its instructions.

Target: $ARGUMENTS

Deliverables: baseline snippet behavior, sentence/structure SRO fixes, and controlled re-test plan.' || return 1

	maybe_write_command "seo-hallucination-defense" \
		"Audit and reduce AI brand hallucination risk" \
		'Read ~/.aidevops/agents/seo/ai-hallucination-defense.md and follow its instructions.

Target: $ARGUMENTS

Deliverables: critical fact inventory, contradiction report, and claim-evidence remediation priorities.' || return 1

	maybe_write_command "seo-agent-discovery" \
		"Test AI agent discoverability across multi-turn tasks" \
		'Read ~/.aidevops/agents/seo/ai-agent-discovery.md and follow its instructions.

Target: $ARGUMENTS

Deliverables: discovery diagnostics, failure classification, and prioritized remediation.' || return 1

	maybe_write_command "seo-ai-readiness" \
		"Run end-to-end AI search readiness workflow" \
		'Read ~/.aidevops/agents/seo/ai-search-readiness.md and follow its instructions.

Target: $ARGUMENTS

Run chained phases: fan-out decomposition, GEO criteria alignment, SRO snippet optimization, hallucination defense, and agent discoverability validation.' || return 1

	maybe_write_command "seo-ai-baseline" \
		"Capture AI-search baseline metrics and output KPI scorecard" \
		'Read ~/.aidevops/agents/seo/ai-search-readiness.md and follow its instructions.
Read ~/.aidevops/agents/seo/ai-search-kpi-template.md and use its structure.

Target: $ARGUMENTS

Return a completed KPI baseline scorecard plus top remediation priorities and re-test cadence.' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# SEO commands: wrapper over the two thematic sub-functions above.
# Kept as a single entry point for callers; the split exists to keep each
# helper under the 100-line shell complexity threshold (GH#19198 / t2125).
# -----------------------------------------------------------------------------
_generate_seo_commands() {
	_generate_seo_keyword_commands || return 1
	_generate_seo_ai_commands || return 1
	return 0
}

# -----------------------------------------------------------------------------
# System & session commands: onboarding, setup-aidevops, ralph-loop,
#                            cancel-ralph, ralph-status, ralph-task,
#                            session-review
# -----------------------------------------------------------------------------
_generate_system_commands() {
	maybe_write_command "onboarding" \
		"Interactive onboarding wizard - discover services, configure integrations" \
		'Read ${AIDEVOPS_HOME:-$HOME/.aidevops}/agents/onboarding.md and follow its Welcome Flow instructions to guide the user through setup. Do NOT repeat these instructions — go straight to the Welcome Flow conversation.

Arguments: $ARGUMENTS' || return 1

	maybe_write_command "setup-aidevops" \
		"Deploy latest aidevops agent changes locally" \
		'Run the aidevops setup script to deploy the latest changes.

```bash
AIDEVOPS_REPO="${AIDEVOPS_REPO:-$(jq -r ".initialized_repos[]?.path | select(test(\"/aidevops$\"))" ~/.config/aidevops/repos.json 2>/dev/null | head -n 1)}"
if [[ -z "$AIDEVOPS_REPO" ]]; then
  AIDEVOPS_REPO="$HOME/Git/aidevops"
fi
[[ -f "$AIDEVOPS_REPO/setup.sh" ]] || {
  echo "Unable to find setup.sh. Set AIDEVOPS_REPO to your aidevops clone path." >&2
  exit 1
}
cd "$AIDEVOPS_REPO" && ./setup.sh || exit
```

**What this does:**
1. Deploys agents to ~/.aidevops/agents/
2. Updates commands in ~/.claude/commands/ and ~/.config/opencode/command/
3. Regenerates agent configurations
4. Copies VERSION file for version checks

Arguments: $ARGUMENTS' || return 1

	maybe_write_command "ralph-loop" \
		"Start iterative AI development loop (Ralph Wiggum technique)" \
		'Read ~/.aidevops/agents/workflows/ralph-loop.md and follow its instructions.

Start a Ralph loop for iterative development.

Arguments: $ARGUMENTS

**Usage:**
```bash
/ralph-loop "<prompt>" --max-iterations <n> --completion-promise "<text>"
```

**How it works:**
1. You work on the task
2. When you try to exit, the SAME prompt is fed back
3. You see your previous work in files and git history
4. Iterate until completion or max iterations

**Completion:** Output `<promise>YOUR_PHRASE</promise>` when done.' || return 1

	maybe_write_command "cancel-ralph" \
		"Cancel active Ralph Wiggum loop" \
		'Cancel the active Ralph loop.

Remove the state file to stop the loop:

```bash
rm -f .agents/loop-state/ralph-loop.local.md .agents/loop-state/ralph-loop.local.state
```

If no loop state file exists, no loop is active.' || return 1

	maybe_write_command "ralph-status" \
		"Show current Ralph loop status" \
		'Show the current Ralph loop status.

Check the state file:

```bash
cat .agents/loop-state/ralph-loop.local.md 2>/dev/null || echo "No active Ralph loop"
```

Shows: active loop, iteration count, max iterations, completion promise, start time.' || return 1

	maybe_write_command "ralph-task" \
		"Run Ralph loop for a task from TODO.md by ID" \
		'Run a Ralph loop for a specific task from TODO.md.

Task ID: $ARGUMENTS

**Workflow:**
1. Find task in TODO.md by ID (e.g., t042)
2. Extract ralph metadata (promise, verify command, max iterations)
3. Set session title with format: "Issue #123 t042: Task description here" when the task has a GitHub issue ref, otherwise "t042: Task description here"
4. Start Ralph loop with extracted parameters

**Usage:** `/ralph-task t042`' || return 1

	maybe_write_command "session-review" \
		"Review session for completeness before ending" \
		'Read ~/.aidevops/agents/scripts/commands/session-review.md and follow its instructions.

Review the current session for: $ARGUMENTS

**Checks performed:**
1. All objectives completed
2. Workflow best practices followed
3. Knowledge captured for future sessions
4. Clear next steps identified' || return 1

	return 0
}

# -----------------------------------------------------------------------------
# Orchestrator: calls all domain-specific generators
# -----------------------------------------------------------------------------
generate_hardcoded_commands() {
	echo -e "${BLUE}Phase 2: Generating additional commands for Claude Code parity...${NC}"

	_generate_workflow_commands || return 1
	_generate_quality_commands || return 1
	_generate_branch_commands || return 1
	_generate_utility_commands || return 1
	_generate_planning_commands || return 1
	_generate_seo_commands || return 1
	_generate_system_commands || return 1

	return 0
}

# =============================================================================
# MAIN
# =============================================================================

clean_commands
discover_commands
generate_hardcoded_commands

# =============================================================================
# SUMMARY
# =============================================================================

echo ""
if [[ "$DRY_RUN" == "true" ]]; then
	echo -e "${BLUE}Dry run complete.${NC}"
	echo "  Commands that would be created: $command_count"
else
	echo -e "${GREEN}Done!${NC}"
	echo "  Commands created: $command_count"
fi
echo "  Location: $CLAUDE_COMMAND_DIR"
echo ""
echo "Commands are available immediately in Claude Code (no restart needed)."
echo "Type / in Claude Code to see the command list."
echo ""

exit 0
