#!/usr/bin/env bash
# opencode-kit init — scaffold orchestration framework
# Flow: check requirements → credentials → copy skills/agents → create opencode.json
# Usage: npx opencode-kit init [--force]
#   --force  Overwrite existing .opencode/ (backup + clean)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
KIT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
MANIFEST="$KIT_DIR/superpowers-contract.json"
. "$SCRIPT_DIR/platform.sh"
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
FORCE=false
for arg in "$@"; do [ "$arg" = "--force" ] && FORCE=true; done
TIMESTAMP=$(date +%Y%m%d%H%M%S)
echo -e "${CYAN}[opencode-kit] Initializing in ${PWD}${NC}"

# ═══════════════════════════════════════════════════════════
# PHASE 1: CHECK REQUIREMENTS
# ═══════════════════════════════════════════════════════════
echo -e "\n${CYAN}[1/5] Checking requirements...${NC}"
deps_ok=true
for cmd in git node python3; do
  if command -v "$cmd" &>/dev/null; then
    echo "  ✅ $cmd: $(command -v "$cmd")"
  else
    echo "  ❌ $cmd: NOT FOUND"
    deps_ok=false
  fi
done
if command -v lean-ctx &>/dev/null; then
  echo "  ✅ lean-ctx: $(command -v "lean-ctx")"
else
  echo -e "  ${YELLOW}⚠️  lean-ctx: not found (optional, but recommended)${NC}"
  echo "  Install: https://github.com/ikieaneh/lean-ctx"
fi
if [ "$deps_ok" = false ]; then
  echo -e "\n${RED}❌ Missing requirements. Install and retry.${NC}"
  exit 1
fi
if ! git rev-parse --git-dir &>/dev/null; then
  git init -q && echo "  ✅ git initialized"
fi

# ═══════════════════════════════════════════════════════════
# PHASE 1b: VALIDATE VERSION (warn-only — update via update.sh)
# ═══════════════════════════════════════════════════════════
echo -e "\n${CYAN}[1b/5] Checking for latest opencode-kit...${NC}"

# Read current installed version from package.json if it exists
CURRENT_VER=""
if [ -f "package.json" ]; then
  CURRENT_VER=$(python3 -c "import json; print(json.load(open('package.json')).get('version',''))" 2>/dev/null) || true
fi
[ -z "$CURRENT_VER" ] && CURRENT_VER="unknown"
echo "  Current version: v${CURRENT_VER}"

# Sentinel guard: prevents re-init loop on cache clear + re-fetch
SENTINEL_DIR="$HOME/.cache/opencode/sentinels"
mkdir -p "$SENTINEL_DIR"
SENTINEL_FILE="$SENTINEL_DIR/$(basename "$(pwd)")"

# Fetch latest from npm registry
echo "  Fetching latest from npm..."
LATEST_VER=$(npm view @ikieaneh/opencode-kit version 2>/dev/null) || true

if [ -z "$LATEST_VER" ]; then
  echo -e "  ${YELLOW}⚠️  Cannot reach npm registry — version check skipped${NC}"
elif [ "$CURRENT_VER" = "$LATEST_VER" ]; then
  echo "  ✅ Already on latest (v${LATEST_VER})"
  # Clear sentinel if version caught up (allows fresh update next time)
  [ -f "$SENTINEL_FILE" ] && rm -f "$SENTINEL_FILE"
elif [ -f "$SENTINEL_FILE" ] && [ "$(cat "$SENTINEL_FILE")" = "$LATEST_VER" ]; then
  echo "  ✅ Version v${LATEST_VER} already processed (sentinel)."
  echo "     Run 'bash .opencode/src/update.sh' to re-apply."
elif [ ! -f "package.json" ]; then
  echo -e "  ${YELLOW}⚠️  No package.json found — skipping version check${NC}"
  echo "  Create one with: npm init -y"
else
  echo -e "  ${YELLOW}⚠️  Version mismatch: v${CURRENT_VER} → v${LATEST_VER}${NC}"
  echo ""
  echo "  Run one of:"
  echo "    bash .opencode/src/update.sh"
  echo "    npm install @ikieaneh/opencode-kit@latest --save"
  echo ""
  echo -e "  ${YELLOW}⚠️  Auto-update removed from init. Use update.sh to avoid re-init loops.${NC}"
fi

# ═══════════════════════════════════════════════════════════
# PHASE 2: PREPARE CREDENTIALS
# ═══════════════════════════════════════════════════════════
echo -e "\n${CYAN}[2/5] Checking credentials...${NC}"
if [ -n "${FIRECRAWL_API_KEY:-}" ] || ([ -f ".env" ] && grep -q "FIRECRAWL_API_KEY" .env 2>/dev/null); then
  echo "  ✅ FIRECRAWL_API_KEY"
else
  echo -e "  ${YELLOW}⚠️  FIRECRAWL_API_KEY not set (web search limited)${NC}"
fi
if [ -n "${GITHUB_TOKEN:-}" ] || ([ -f ".env" ] && grep -q "GITHUB_TOKEN" .env 2>/dev/null); then
  echo "  ✅ GITHUB_TOKEN"
else
  echo -e "  ${YELLOW}⚠️  GITHUB_TOKEN not set (GitHub API limited)${NC}"
fi

# ═══════════════════════════════════════════════════════════
# AUTO-UPDATE: Compare installed vs package version
# ═══════════════════════════════════════════════════════════
INSTALLED_VER=""
[ -f ".opencode/orchestration/contract.json" ] && INSTALLED_VER=$(python3 -c "import json; print(json.load(open('.opencode/orchestration/contract.json')).get('contract_version',''))" 2>/dev/null)
PACKAGE_VER=$(python3 -c "import json; print(json.load(open('$MANIFEST')).get('version',''))" 2>/dev/null)

# Sentinel check: skip auto-update if already done for this version
SENTINEL_DIR="$HOME/.cache/opencode/sentinels"
SENTINEL_FILE="$SENTINEL_DIR/$(basename "$(pwd)")"

if [ -n "$INSTALLED_VER" ] && [ -n "$PACKAGE_VER" ] && [ "$INSTALLED_VER" != "$PACKAGE_VER" ]; then
  # Skip if sentinel exists for this version
  if [ -f "$SENTINEL_FILE" ] && [ "$(cat "$SENTINEL_FILE")" = "$PACKAGE_VER" ]; then
    echo -e "  ✅ Already up to date (v$PACKAGE_VER, sentinel)"
  else
    echo -e "\n${CYAN}[auto-update] $INSTALLED_VER → $PACKAGE_VER${NC}"

    # Update scripts (overwrite with latest)
    UPDATED_SCRIPTS=0
    for f in $(python3 -c "import json; [print(s) for s in json.load(open('$MANIFEST'))['scripts']]" 2>/dev/null); do
      if [ -f "$KIT_DIR/src/$f" ]; then
        cp "$KIT_DIR/src/$f" ".opencode/src/$f"
        chmod +x ".opencode/src/$f"
        UPDATED_SCRIPTS=$((UPDATED_SCRIPTS + 1))
      fi
    done
    for f in $(python3 -c "import json; [print(p) for p in json.load(open('$MANIFEST'))['python_scripts']]" 2>/dev/null); do
      if [ -f "$KIT_DIR/src/$f" ]; then
        cp "$KIT_DIR/src/$f" ".opencode/src/$f"
        chmod +x ".opencode/src/$f"
        UPDATED_SCRIPTS=$((UPDATED_SCRIPTS + 1))
      fi
    done
    echo "  ✅ Updated $UPDATED_SCRIPTS scripts"

    # Update plugin
    if [ -f "$KIT_DIR/.opencode/plugins/opencode-kit.js" ]; then
      mkdir -p .opencode/plugins
      cp "$KIT_DIR/.opencode/plugins/opencode-kit.js" ".opencode/plugins/opencode-kit.js"
      echo "  ✅ Updated plugin"
    fi

    # Update rules (merge)
    for f in $(python3 -c "import json; [print(r) for r in json.load(open('$MANIFEST'))['rules']]" 2>/dev/null); do
      src="$KIT_DIR/rules/$f"
      dst=".opencode/rules/$f"
      if [ -f "$dst" ]; then
        bash "$SCRIPT_DIR/merge-config.sh" "$src" "$dst" "$dst" 2>/dev/null
      else
        [ -f "$src" ] && cp "$src" "$dst"
      fi
    done
    echo "  ✅ Updated rules"

    # Update contract version
    python3 -c "
import json
p = '.opencode/orchestration/contract.json'
d = json.load(open(p))
d['contract_version'] = '$PACKAGE_VER'
json.dump(d, open(p,'w'), indent=2)
" 2>/dev/null

    # Write sentinel to prevent re-trigger on re-init
    mkdir -p "$SENTINEL_DIR"
    echo "$PACKAGE_VER" > "$SENTINEL_FILE"

    echo -e "  ${GREEN}✅ Updated to v$PACKAGE_VER${NC}"
  fi
elif [ -n "$INSTALLED_VER" ]; then
  echo -e "  ✅ Already up to date (v$INSTALLED_VER)"
  # Clear sentinel if version matches (allows fresh future update)
  [ -f "$SENTINEL_FILE" ] && rm -f "$SENTINEL_FILE"
fi

# ═══════════════════════════════════════════════════════════
# PHASE 3: COPY SKILLS AND AGENTS
# ═══════════════════════════════════════════════════════════
echo -e "\n${CYAN}[3/5] Copying skills and agents...${NC}"
if [ -d ".opencode" ]; then
  if [ "$FORCE" = true ]; then
    cp -r ".opencode" ".opencode.bak.$TIMESTAMP"
    rm -rf ".opencode"
    echo "  ✅ Backup: .opencode.bak.$TIMESTAMP"
  else
    echo -e "  ${YELLOW}⚠️  .opencode/ exists. Use --force to re-scaffold.${NC}"
  fi
fi
mkdir -p .opencode/{orchestration,rules,agents,skills,src,templates}
# Agents (additive: don't overwrite existing)
for agent in "$KIT_DIR"/agents/*.md; do
  dest=".opencode/agents/$(basename "$agent")"
  if [ ! -f "$dest" ]; then
    cp "$agent" "$dest"
    echo "  + $(basename "$agent")"
  fi
done
echo "  ✅ agents/ ($(ls .opencode/agents/*.md 2>/dev/null | wc -l | tr -d ' ') agents)"
# Skills
for skill_dir in "$KIT_DIR"/skills/*/; do
  skill_name=$(basename "$skill_dir")
  if [ "$skill_name" != "__pycache__" ] && [ ! -d ".opencode/skills/$skill_name" ]; then
    cp -r "$skill_dir" ".opencode/skills/$skill_name"
  fi
done
echo "  ✅ skills/ ($(ls -d .opencode/skills/*/ 2>/dev/null | wc -l | tr -d ' ') skills)"
# Rules (merge with existing via merge-config.sh)
for f in $(python3 -c "import json; [print(r) for r in json.load(open('$MANIFEST'))['rules']]" 2>/dev/null); do
  src="$KIT_DIR/rules/$f"
  dst=".opencode/rules/$f"
  if [ -f "$dst" ]; then
    bash "$SCRIPT_DIR/merge-config.sh" "$src" "$dst" "$dst"
  elif [ -f "$src" ]; then
    cp "$src" "$dst"
  fi
done
echo "  ✅ rules/ ($(python3 -c "import json,sys; print(len(json.load(sys.stdin)['rules']))" < "$MANIFEST") rule files)"
# Contract (merge with existing via merge-config.sh)
python3 -c "
import json, os, subprocess
# Add _meta.extends to existing rule files
for f in ['rules/rules.json', 'rules/workflow-rules.json', 'rules/agent-rules.json', 'rules/learner-rules.json']:
    p = '.opencode/' + f
    if os.path.exists(p):
        d = json.load(open(p)); d.setdefault('_meta',{})['extends']='opencode-kit'
        json.dump(d, open(p,'w'), indent=2)
# Handle contract.json: merge if user has existing, otherwise copy from kit
src = '$KIT_DIR/contract.json'
dst = '.opencode/orchestration/contract.json'
src_dir = '$SCRIPT_DIR'
if os.path.exists(dst) and os.path.exists(src):
    subprocess.run(['bash', src_dir + '/merge-config.sh', src, dst, dst], check=True)
    d = json.load(open(dst))
    d.setdefault('_meta',{})['extends'] = 'opencode-kit'
    json.dump(d, open(dst, 'w'), indent=2)
elif os.path.exists(src):
    d = json.load(open(src))
    d.setdefault('_meta',{})['extends'] = 'opencode-kit'
    json.dump(d, open(dst, 'w'), indent=2)
print('  ✅ _meta.extends set')
" 2>/dev/null
# Scripts
for f in $(python3 -c "import json; [print(s) for s in json.load(open('$MANIFEST'))['scripts']]"); do
  [ -f "$KIT_DIR/src/$f" ] && cp "$KIT_DIR/src/$f" ".opencode/src/$f" && chmod +x ".opencode/src/$f"
done
# Copy Python scripts
for f in $(python3 -c "import json; [print(p) for p in json.load(open('$MANIFEST'))['python_scripts']]"); do
  [ -f "$KIT_DIR/src/$f" ] && cp "$KIT_DIR/src/$f" ".opencode/src/$f" && chmod +x ".opencode/src/$f"
done
echo "  ✅ src/ (scripts)"
# Git hooks
if [ -d "$KIT_DIR/.githooks" ]; then
  cp -r "$KIT_DIR/.githooks" .githooks && chmod +x .githooks/* && git config core.hooksPath .githooks
  echo "  ✅ .githooks/"
fi

# ═══════════════════════════════════════════════════════════
# PHASE 4: CREATE OR UPDATE OPENCODE.JSON
# ═══════════════════════════════════════════════════════════
echo -e "\n${CYAN}[4/5] Generating opencode.json...${NC}"
if [ -f "opencode.json" ]; then
  cp opencode.json "opencode.json.backup.$TIMESTAMP"
  bash "$KIT_DIR/src/generate-opencode-json.sh" "$KIT_DIR/opencode.json.template" "opencode.json"
  echo "  ✅ opencode.json merged (backup saved)"
else
  bash "$KIT_DIR/src/generate-opencode-json.sh" "$KIT_DIR/opencode.json.template" "opencode.json"
  echo "  ✅ opencode.json created"
fi

# ═══════════════════════════════════════════════════════════
# PHASE 5: VERIFY
# ═══════════════════════════════════════════════════════════
echo -e "\n${CYAN}[5/5] Verifying...${NC}"
echo "  Agents:  $(ls .opencode/agents/*.md 2>/dev/null | wc -l | tr -d ' ')"
echo "  Skills:  $(ls -d .opencode/skills/*/ 2>/dev/null | wc -l | tr -d ' ')"
echo "  Rules:   $(ls .opencode/rules/*.json 2>/dev/null | wc -l | tr -d ' ')"
echo "  Scripts: $(ls .opencode/src/*.sh 2>/dev/null | wc -l | tr -d ' ')"
echo -e "\n${GREEN}✅ opencode-kit initialized${NC}"
echo ""
echo "  opencode.json has:"
echo "  • $(python3 -c "import json; print(len(json.load(open('$MANIFEST'))['agents']))") agents (skills + tools, model from your global config)"
echo "  • $(python3 -c "import json; print(len(json.load(open('$MANIFEST'))['slash_commands']))") slash commands (/opencode-kit:*)"
echo "  • $(python3 -c "import json; print(len(json.load(open('$MANIFEST'))['mcps']))") MCPs (lean-ctx, gitnexus, context7, firecrawl, graphify)"
echo ""
echo "  Next:"
echo "  1. Set GOAL & SCOPE in .opencode/orchestration/contract.json"
echo "  2. Configure credentials (FIRECRAWL_API_KEY, GITHUB_TOKEN)"
echo "  3. Start opencode"