#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
AGENTS_DIR="$ROOT_DIR/.agents"
SPRINT_DIR="$AGENTS_DIR/sprints/widget-field-refactor"
ACTIVE_CONFIG="$AGENTS_DIR/config.toml"
GPT54_CONFIG="$AGENTS_DIR/config.gpt-5.4.toml"
BACKUP_CONFIG="$AGENTS_DIR/config.toml.pre-gpt-5.4.bak"
CODEX_CONFIG="$HOME/.codex/config.toml"

require_file() {
  local path="$1"
  if [[ ! -f "$path" ]]; then
    echo "Missing required file: $path" >&2
    exit 1
  fi
}

require_cmd() {
  local name="$1"
  if ! command -v "$name" >/dev/null 2>&1; then
    echo "Missing required command: $name" >&2
    exit 1
  fi
}

spawn_agent() {
  local type="$1"
  local name="$2"

  echo "  - spawning $name ($type)"
  npx @claude-flow/cli agent spawn --type "$type" --name "$name"
}

check_azure_codex_config() {
  require_file "$CODEX_CONFIG"

  local provider
  provider="$(sed -n 's/^[[:space:]]*model_provider[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$CODEX_CONFIG" | head -n 1)"

  if [[ -z "$provider" ]]; then
    echo "Missing model_provider in $CODEX_CONFIG" >&2
    echo "See docs/azure_codex_setup.md" >&2
    exit 1
  fi

  if [[ "$provider" != azure* ]]; then
    echo "Codex is not configured for Azure in $CODEX_CONFIG" >&2
    echo "Detected model_provider=\"$provider\"" >&2
    echo "See docs/azure_codex_setup.md" >&2
    exit 1
  fi

  if ! grep -q 'AZURE_OPENAI_API_KEY' "$CODEX_CONFIG"; then
    echo "Azure Codex config is missing AZURE_OPENAI_API_KEY binding in $CODEX_CONFIG" >&2
    echo "See docs/azure_codex_setup.md" >&2
    exit 1
  fi

  if [[ -z "${AZURE_OPENAI_API_KEY:-}" ]]; then
    echo "AZURE_OPENAI_API_KEY is not exported in the current shell." >&2
    echo "See docs/azure_codex_setup.md" >&2
    exit 1
  fi

  echo "Azure Codex config detected:"
  echo "  config   -> $CODEX_CONFIG"
  echo "  provider -> $provider"
}

require_cmd npx
require_file "$GPT54_CONFIG"
require_file "$SPRINT_DIR/O1-orchestrator.md"
require_file "$SPRINT_DIR/A1-architect.md"
require_file "$SPRINT_DIR/C1-field-domain-coder.md"
require_file "$SPRINT_DIR/C2-blueprint-ui-coder.md"
require_file "$SPRINT_DIR/C3-widget-platform-coder.md"
require_file "$SPRINT_DIR/C4-dashboard-data-coder.md"
require_file "$SPRINT_DIR/T1-test-agent.md"
require_file "$SPRINT_DIR/R1-reviewer.md"
check_azure_codex_config

if [[ -f "$ACTIVE_CONFIG" && ! -f "$BACKUP_CONFIG" ]]; then
  cp "$ACTIVE_CONFIG" "$BACKUP_CONFIG"
fi

echo "Switching active Claude Flow config to GPT-5.4..."
cp "$GPT54_CONFIG" "$ACTIVE_CONFIG"

echo
echo "Initializing hierarchical swarm..."
npx @claude-flow/cli swarm init \
  --topology hierarchical \
  --max-agents 8 \
  --strategy specialized

echo
echo "Spawning sprint agents..."
spawn_agent coordinator O1
spawn_agent architect A1
spawn_agent coder C1
spawn_agent coder C2
spawn_agent coder C3
spawn_agent coder C4
spawn_agent tester T1
spawn_agent reviewer R1

echo
echo "Swarm status:"
npx @claude-flow/cli swarm status

echo
echo "Active agents:"
npx @claude-flow/cli agent list --filter active || true

echo
echo "Important:"
echo "  'swarm init' only creates the coordination container."
echo "  Actual progress starts only after agents are successfully created"
echo "  and given work."

echo
echo "Sprint prompt files:"
echo "  O1 -> $SPRINT_DIR/O1-orchestrator.md"
echo "  A1 -> $SPRINT_DIR/A1-architect.md"
echo "  C1 -> $SPRINT_DIR/C1-field-domain-coder.md"
echo "  C2 -> $SPRINT_DIR/C2-blueprint-ui-coder.md"
echo "  C3 -> $SPRINT_DIR/C3-widget-platform-coder.md"
echo "  C4 -> $SPRINT_DIR/C4-dashboard-data-coder.md"
echo "  T1 -> $SPRINT_DIR/T1-test-agent.md"
echo "  R1 -> $SPRINT_DIR/R1-reviewer.md"

echo
echo "Recommended startup sequence:"
echo "  1. Paste O1 prompt into agent O1."
echo "  2. Paste A1 prompt into agent A1."
echo "  3. Wait for A1 contracts."
echo "  4. Then start C1, C3, and T1."
echo "  5. Start C2 after field contract approval."
echo "  6. Start C4 after router/application boundaries are agreed."
echo "  7. Keep R1 reviewing every merge candidate."

echo
echo "Note:"
echo "  This script automates config activation, swarm init, and agent spawning."
echo "  Prompt injection remains file-based because the repo-local Claude Flow"
echo "  docs only define swarm init, agent spawn, task orchestration, status,"
echo "  and routing commands."
echo "  O1 uses the CLI's 'coordinator' type and receives the non-coding"
echo "  orchestrator instructions from O1-orchestrator.md."
