#!/usr/bin/env bash
# ketacli setup — install ketacli skills for various AI coding agents
set -e
umask 077

# Try to find ketacli package directory using Python
INSTALL_DIR=$(python3 -c "import ketacli; import os; print(os.path.dirname(ketacli.__file__))" 2>/dev/null)

# Fallback to common locations
if [ -z "$INSTALL_DIR" ] || [ ! -d "$INSTALL_DIR/skills" ]; then
    for dir in /usr/local/lib/python*/site-packages/ketacli \
               /usr/lib/python*/site-packages/ketacli \
               "$HOME/Library/Python/*/lib/python/site-packages/ketacli" \
               "$HOME/.local/lib/python*/site-packages/ketacli"; do
        if [ -d "$dir/skills" ]; then
            INSTALL_DIR="$dir"
            break
        fi
    done
fi

# Last fallback: try to find from script location
if [ -z "$INSTALL_DIR" ] || [ ! -d "$INSTALL_DIR/skills" ]; then
    SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"
    SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
    # For venv: .venv/bin -> .venv/lib/pythonX.X/site-packages
    if [ -f "$SCRIPT_DIR/../../lib/python*/site-packages/ketacli/__init__.py" ]; then
        INSTALL_DIR="$(echo $SCRIPT_DIR/../../lib/python*/site-packages/ketacli)"
        INSTALL_DIR=${INSTALL_DIR%%/}  # Remove trailing glob
    fi
fi

# ─── Parse flags ──────────────────────────────────────────────
HOST="auto"
LOCAL_INSTALL=0
SKILL_PREFIX=0
QUIET=0

while [ $# -gt 0 ]; do
  case "$1" in
    --host) HOST="$2"; shift 2 ;;
    --host=*) HOST="${1#--host=}"; shift ;;
    --local) LOCAL_INSTALL=1; shift ;;
    -q|--quiet) QUIET=1; shift ;;
    *) shift ;;
  esac
done

log() { [ "$QUIET" -eq 0 ] && echo "$@" || true; }

# ─── Detect available agents ───────────────────────────────────
INSTALL_OPENCODE=0
INSTALL_CLAUDE=0
INSTALL_CODEX=0
INSTALL_OPENCLAW=0
INSTALL_QCLAW=0

if [ "$HOST" = "auto" ]; then
  command -v opencode >/dev/null 2>&1 && INSTALL_OPENCODE=1
  command -v claude >/dev/null 2>&1 && INSTALL_CLAUDE=1
  command -v codex >/dev/null 2>&1 && INSTALL_CODEX=1
  command -v openclaw >/dev/null 2>&1 && INSTALL_OPENCLAW=1
  [ -d "$HOME/.qclaw/workspace/skills" ] && INSTALL_QCLAW=1
  
  # Default to opencode if none found
  if [ "$INSTALL_OPENCODE" -eq 0 ] && [ "$INSTALL_CLAUDE" -eq 0 ] && [ "$INSTALL_CODEX" -eq 0 ] && [ "$INSTALL_OPENCLAW" -eq 0 ] && [ "$INSTALL_QCLAW" -eq 0 ]; then
    INSTALL_OPENCODE=1
  fi
elif [ "$HOST" = "opencode" ]; then
  INSTALL_OPENCODE=1
elif [ "$HOST" = "claude" ]; then
  INSTALL_CLAUDE=1
elif [ "$HOST" = "codex" ]; then
  INSTALL_CODEX=1
elif [ "$HOST" = "openclaw" ]; then
  INSTALL_OPENCLAW=1
elif [ "$HOST" = "qclaw" ]; then
  INSTALL_QCLAW=1
fi

# ─── Copy skill files ─────────────────────────────────────────────
copy_skill_files() {
  local source_dir="$1"
  local skills_dir="$2"
  local copied=()
  
  mkdir -p "$skills_dir"
  
  for skill_dir in "$INSTALL_DIR"/skills/*/; do
    if [ -f "$skill_dir/SKILL.md" ]; then
      dir_name="$(basename "$skill_dir")"
      
      # Skip ketacli-dev
      if [ "$dir_name" = "ketacli-dev" ]; then
        continue
      fi
      
      target="$skills_dir/$dir_name/SKILL.md"
      
      # Create directory and copy SKILL.md
      mkdir -p "$skills_dir/$dir_name"
      rm -f "$target"
      cp "$skill_dir/SKILL.md" "$target"
      copied+=("$dir_name")
    fi
  done
  
  if [ ${#copied[@]} -gt 0 ]; then
    log "  copied skills: ${copied[*]}"
  fi
}

# ─── Install for OpenCode ────────────────────────────────────────
if [ "$INSTALL_OPENCODE" -eq 1 ]; then
  log "Installing ketacli skills for OpenCode..."
  
  OPENCODE_SKILLS="$HOME/.config/opencode/skills"
  copy_skill_files "$INSTALL_DIR" "$OPENCODE_SKILLS"
  
  log "  installed to: $OPENCODE_SKILLS"
fi

# ─── Install for Claude Code ─────────────────────────────────────
if [ "$INSTALL_CLAUDE" -eq 1 ]; then
  log "Installing ketacli skills for Claude Code..."
  
  CLAUDE_SKILLS="$HOME/.claude/skills"
  copy_skill_files "$INSTALL_DIR" "$CLAUDE_SKILLS"
  
  log "  installed to: $CLAUDE_SKILLS"
fi

# ─── Install for Codex CLI ──────────────────────────────────────
if [ "$INSTALL_CODEX" -eq 1 ]; then
  log "Installing ketacli skills for OpenAI Codex CLI..."
  
  CODEX_SKILLS="$HOME/.codex/skills/ketacli"
  mkdir -p "$CODEX_SKILLS"
  
  # Create .agents format for Codex
  AGENTS_DIR="$CODEX_SKILLS/.agents/skills"
  mkdir -p "$AGENTS_DIR"
  
  for skill_dir in "$INSTALL_DIR"/skills/*/; do
    if [ -f "$skill_dir/SKILL.md" ]; then
      skill_name="$(basename "$skill_dir")"
      
      # Skip ketacli-dev
      if [ "$skill_name" = "ketacli-dev" ]; then
        continue
      fi
      
      # Rename spl-search to ketacli-spl
      if [ "$skill_name" = "spl-search" ]; then
        skill_name="ketacli-spl"
      fi
      
      # Copy SKILL.md (Codex doesn't support symlinks well)
      mkdir -p "$AGENTS_DIR/ketacli-$skill_name"
      cp "$skill_dir/SKILL.md" "$AGENTS_DIR/ketacli-$skill_name/SKILL.md"
    fi
  done
  
  log "  installed to: $CODEX_SKILLS"
fi

# ─── Install for OpenClaw ───────────────────────────────────────
if [ "$INSTALL_OPENCLAW" -eq 1 ]; then
  log "Installing ketacli skills for OpenClaw..."
  
  OPENCLAW_SKILLS="$HOME/.openclaw/skills"
  copy_skill_files "$INSTALL_DIR" "$OPENCLAW_SKILLS"
  
  log "  installed to: $OPENCLAW_SKILLS"
fi

# ─── Install for qclaw ───────────────────────────────────────────
if [ "$INSTALL_QCLAW" -eq 1 ]; then
  log "Installing ketacli skills for qclaw..."
  
  QCLAW_SKILLS="$HOME/.qclaw/workspace/skills"
  copy_skill_files "$INSTALL_DIR" "$QCLAW_SKILLS"
  
  log "  installed to: $QCLAW_SKILLS"
fi

log "Done! ketacli skills installed."
log ""
log "Available skills:"
log "  - /ketacli-manage : KetaDB resource management (CRUD)"
log "  - /ketacli-mock   : Mock data generation"
log "  - /ketacli-dc-task: Collection task management"
log "  - /ketacli-alerts : KetaDB alerts management"
log "  - /ketacli-spl    : SPL search query"
