#!/usr/bin/env bash
#
# APS Update Script
# Updates templates, rules, and skill in an existing APS project.
# Your specs (index.aps.md, modules/*.aps.md) are preserved.
#
# Usage:
#   curl -fsSL https://raw.githubusercontent.com/EddaCraft/anvil-plan-spec/main/scaffold/update | bash
#   curl ... | bash -s -- ./my-project
#   curl ... | VERSION=0.2.0 bash
#
# For new projects, use the install script instead.
#

set -euo pipefail

VERSION="${VERSION:-main}"
GLOBAL_INSTALL=false
TARGET="."

# Parse flags
for arg in "$@"; do
  case "$arg" in
    --global|-g) GLOBAL_INSTALL=true ;;
    *) TARGET="$arg" ;;
  esac
done

# Validate TARGET (only for project-scoped updates)
if [[ "$GLOBAL_INSTALL" == false ]]; then
  if [[ "$TARGET" == /* ]]; then
    echo "error: Absolute paths are not allowed for TARGET; please use a relative path (e.g., ./my-project)." >&2
    exit 1
  fi

  if [[ "$TARGET" == *".."* ]]; then
    echo "error: Parent directory references ('..') are not allowed in TARGET." >&2
    exit 1
  fi
fi

PLANS_DIR="$TARGET/plans"
BASE_URL="https://raw.githubusercontent.com/EddaCraft/anvil-plan-spec/$VERSION"

# Colors (disabled if not interactive)
if [[ -t 1 ]]; then
  GREEN='\033[0;32m'
  RED='\033[0;31m'
  BLUE='\033[0;34m'
  YELLOW='\033[1;33m'
  BOLD='\033[1m'
  NC='\033[0m'
else
  GREEN='' RED='' BLUE='' YELLOW='' BOLD='' NC=''
fi

info()  { echo -e "${GREEN}>${NC} $1"; }
warn()  { echo -e "${YELLOW}>${NC} $1"; }
error() { echo -e "${RED}error:${NC} $1"; }
step()  { echo -e "${BLUE}==>${NC} ${BOLD}$1${NC}"; }

# Check if APS hooks are already configured in settings
has_aps_hooks() {
  local settings="$TARGET/.claude/settings.local.json"
  [[ -f "$settings" ]] && grep -q 'aps-planning/scripts\|\[APS\]' "$settings" 2>/dev/null
}

# Prompt user with a yes/no question. Returns 0 for yes, 1 for no.
ask_yn() {
  local prompt="$1"
  local default="${2:-n}"

  if [[ -t 0 ]]; then
    local yn_hint
    if [[ "$default" == "y" ]]; then yn_hint="Y/n"; else yn_hint="y/N"; fi
    printf "%s [%s] " "$prompt" "$yn_hint"
    read -r answer
    answer="${answer:-$default}"
    [[ "$answer" =~ ^[Yy] ]]
  else
    [[ "$default" == "y" ]]
  fi
}

download() {
  local path="$1"
  local dest="$2"
  local url="$BASE_URL/scaffold/$path"
  mkdir -p "$(dirname "$dest")"
  if ! curl -fsSL "$url" -o "$dest"; then
    error "Failed to download '$path' from $url"
    echo "       Please check your network connectivity and ensure VERSION='$VERSION' is correct."
    exit 1
  fi
}

# Download from repo root (for non-scaffold files like bin/ and lib/)
download_root() {
  local path="$1"
  local dest="$2"
  local url="$BASE_URL/$path"
  mkdir -p "$(dirname "$dest")"
  if ! curl -fsSL "$url" -o "$dest"; then
    error "Failed to download '$path' from $url"
    echo "       Please check your network connectivity and ensure VERSION='$VERSION' is correct."
    exit 1
  fi
}

# Global update: CLI only
update_global() {
  local aps_home="${APS_HOME:-$HOME/.aps}"

  if [[ ! -d "$aps_home/bin" ]]; then
    error "No global APS installation found at $aps_home"
    echo ""
    echo "To install globally:"
    echo "  curl -fsSL https://raw.githubusercontent.com/EddaCraft/anvil-plan-spec/main/scaffold/install | bash -s -- --global"
    echo ""
    exit 1
  fi

  echo ""
  echo -e "${BOLD}Anvil Plan Spec (APS) Global Update${NC}"
  echo ""

  step "Updating APS CLI at $aps_home"

  for f in bin/aps bin/aps.ps1 lib/output.sh lib/Output.psm1 lib/lint.sh lib/Lint.psm1 lib/orchestrate.sh lib/audit.sh lib/scaffold.sh lib/Scaffold.psm1 lib/rules/common.sh lib/rules/Common.psm1 lib/rules/module.sh lib/rules/Module.psm1 lib/rules/index.sh lib/rules/Index.psm1 lib/rules/workitem.sh lib/rules/WorkItem.psm1 lib/rules/issues.sh lib/rules/Issues.psm1; do
    download_root "$f" "$aps_home/$f"
  done
  chmod +x "$aps_home/bin/aps"

  echo ""
  step "Global update complete"
  info "bin/aps + lib/ updated at $aps_home"
  echo ""
}

# Branch: global update exits early
if [[ "$GLOBAL_INSTALL" == true ]]; then
  update_global
  exit 0
fi

# Header
echo ""
echo -e "${BOLD}Anvil Plan Spec (APS) Update${NC}"
echo ""

# Check for existing installation
if [[ ! -d "$PLANS_DIR" ]]; then
  error "No plans/ directory found at $TARGET"
  echo ""
  echo "To install APS in a new project:"
  echo "  curl -fsSL https://raw.githubusercontent.com/EddaCraft/anvil-plan-spec/main/scaffold/install | bash"
  echo ""
  exit 1
fi

# Ensure subdirectories exist (in case of older installations)
mkdir -p "$PLANS_DIR/modules"
mkdir -p "$PLANS_DIR/execution"
mkdir -p "$PLANS_DIR/decisions"

# Update CLI
step "Updating APS CLI"
for f in bin/aps bin/aps.ps1 lib/output.sh lib/Output.psm1 lib/lint.sh lib/Lint.psm1 lib/orchestrate.sh lib/audit.sh lib/scaffold.sh lib/Scaffold.psm1 lib/rules/common.sh lib/rules/Common.psm1 lib/rules/module.sh lib/rules/Module.psm1 lib/rules/index.sh lib/rules/Index.psm1 lib/rules/workitem.sh lib/rules/WorkItem.psm1 lib/rules/issues.sh lib/rules/Issues.psm1 lib/rules/design.sh lib/rules/Design.psm1; do
  download_root "$f" "$TARGET/$f"
done
chmod +x "$TARGET/bin/aps"
info "bin/aps + lib/ (CLI)"

# Update templates and rules
step "Updating templates and rules"

download "plans/aps-rules.md" "$PLANS_DIR/aps-rules.md"
info "aps-rules.md"

download "plans/modules/.module.template.md" "$PLANS_DIR/modules/.module.template.md"
info "modules/.module.template.md"

download "plans/modules/.simple.template.md" "$PLANS_DIR/modules/.simple.template.md"
info "modules/.simple.template.md"

download "plans/modules/.index-monorepo.template.md" "$PLANS_DIR/modules/.index-monorepo.template.md"
info "modules/.index-monorepo.template.md"

download "plans/execution/.actions.template.md" "$PLANS_DIR/execution/.actions.template.md"
info "execution/.actions.template.md"

# Update skill files
step "Updating APS planning skill"

SKILL_DIR="$TARGET/aps-planning"
COMMANDS_DIR="$TARGET/.claude/commands"

mkdir -p "$SKILL_DIR/scripts"
download "aps-planning/SKILL.md" "$SKILL_DIR/SKILL.md"
download "aps-planning/reference.md" "$SKILL_DIR/reference.md"
download "aps-planning/examples.md" "$SKILL_DIR/examples.md"
download "aps-planning/hooks.md" "$SKILL_DIR/hooks.md"
download "aps-planning/scripts/install-hooks.sh" "$SKILL_DIR/scripts/install-hooks.sh"
download "aps-planning/scripts/init-session.sh" "$SKILL_DIR/scripts/init-session.sh"
download "aps-planning/scripts/check-complete.sh" "$SKILL_DIR/scripts/check-complete.sh"
download "aps-planning/scripts/pre-tool-check.sh" "$SKILL_DIR/scripts/pre-tool-check.sh"
download "aps-planning/scripts/post-tool-nudge.sh" "$SKILL_DIR/scripts/post-tool-nudge.sh"
download "aps-planning/scripts/enforce-plan-update.sh" "$SKILL_DIR/scripts/enforce-plan-update.sh"
download "aps-planning/scripts/install-hooks.ps1" "$SKILL_DIR/scripts/install-hooks.ps1"
download "aps-planning/scripts/init-session.ps1" "$SKILL_DIR/scripts/init-session.ps1"
download "aps-planning/scripts/check-complete.ps1" "$SKILL_DIR/scripts/check-complete.ps1"
download "aps-planning/scripts/pre-tool-check.ps1" "$SKILL_DIR/scripts/pre-tool-check.ps1"
download "aps-planning/scripts/post-tool-nudge.ps1" "$SKILL_DIR/scripts/post-tool-nudge.ps1"
download "aps-planning/scripts/enforce-plan-update.ps1" "$SKILL_DIR/scripts/enforce-plan-update.ps1"
chmod +x "$SKILL_DIR/scripts/"*.sh

info "aps-planning/ (skill, reference, examples, hooks, scripts)"

mkdir -p "$COMMANDS_DIR"
download "commands/plan.md" "$COMMANDS_DIR/plan.md"
download "commands/plan-status.md" "$COMMANDS_DIR/plan-status.md"

info ".claude/commands/ (plan, plan-status)"

# Success
echo ""
step "Update complete"
echo ""
echo "  Updated:"
echo "    - bin/aps + lib/ (CLI)"
echo "    - aps-rules.md (agent guidance)"
echo "    - modules/.module.template.md"
echo "    - modules/.simple.template.md"
echo "    - modules/.index-monorepo.template.md"
echo "    - execution/.actions.template.md"
echo "    - aps-planning/ (skill + scripts)"
echo "    - .claude/commands/ (plan, plan-status)"
echo ""
warn "Your specs were preserved:"
echo "    - index.aps.md"
echo "    - modules/*.aps.md"
echo "    - execution/*.actions.md"
echo ""
# Prompt for hooks if not already configured
if ! has_aps_hooks; then
  echo ""
  if ask_yn "Install APS hooks into .claude/settings.local.json?" "y"; then
    (cd "$TARGET" && bash aps-planning/scripts/install-hooks.sh)
  else
    if ask_yn "Copy hook scripts for you to install/review later?" "y"; then
      info "Hook scripts are at: aps-planning/scripts/"
      echo "    Run ./aps-planning/scripts/install-hooks.sh when ready"
      echo "    See aps-planning/hooks.md for what each hook does"
    else
      info "Skipping hooks. You can install them later:"
      echo "    ./aps-planning/scripts/install-hooks.sh"
    fi
  fi
else
  warn "Hook configuration was NOT modified."
  echo "    To update hooks: ./aps-planning/scripts/install-hooks.sh"
fi
echo ""
