#!/bin/bash
# Aphoria Claude Code Skill Installer
#
# This script installs the Aphoria skill to ~/.claude/skills/aphoria/
# making /aphoria commands available in Claude Code sessions.
#
# Usage:
#   ./install.sh          # Install skill only
#   ./install.sh --build  # Build aphoria binary first, then install skill

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APHORIA_DIR="$(dirname "$SCRIPT_DIR")"
SKILL_DEST="$HOME/.claude/skills/aphoria"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "Aphoria Skill Installer"
echo "======================="
echo ""

# Build aphoria if requested
if [[ "$1" == "--build" ]]; then
    echo -e "${YELLOW}Building aphoria binary...${NC}"
    cd "$APHORIA_DIR"
    cargo build --release

    # Copy binary to cargo bin (optional, makes `aphoria` available globally)
    if [[ -d "$HOME/.cargo/bin" ]]; then
        cp "$APHORIA_DIR/target/release/aphoria" "$HOME/.cargo/bin/"
        echo -e "${GREEN}Installed aphoria binary to ~/.cargo/bin/aphoria${NC}"
    fi
    echo ""
fi

# Check if aphoria binary exists
if ! command -v aphoria &> /dev/null; then
    if [[ -f "$APHORIA_DIR/target/release/aphoria" ]]; then
        echo -e "${YELLOW}Note: aphoria binary found at $APHORIA_DIR/target/release/aphoria${NC}"
        echo "Consider adding to PATH or running with --build flag."
    else
        echo -e "${YELLOW}Warning: aphoria binary not found.${NC}"
        echo "The skill will be installed, but you'll need to build aphoria first:"
        echo "  cd $APHORIA_DIR && cargo build --release"
        echo ""
    fi
fi

# Create skill directory
echo "Installing skill to $SKILL_DEST..."
mkdir -p "$SKILL_DEST"

# Copy skill files
cp "$SCRIPT_DIR/SKILL.md" "$SKILL_DEST/SKILL.md"

# Verify installation
if [[ -f "$SKILL_DEST/SKILL.md" ]]; then
    echo -e "${GREEN}Skill installed successfully!${NC}"
    echo ""
    echo "Available commands:"
    echo "  /aphoria           - Scan current project"
    echo "  /aphoria scan      - Scan current project"
    echo "  /aphoria scan --fix - Scan and offer fixes"
    echo "  /aphoria ack       - Acknowledge a conflict"
    echo "  /aphoria status    - Show status"
    echo "  /aphoria diff      - Show changes since baseline"
    echo ""
    echo "To use in Claude Code, just type /aphoria in a project directory."
else
    echo -e "${RED}Installation failed!${NC}"
    exit 1
fi
