#!/bin/bash

# Unified Agent Integration Setup Script
# Installs and configures Prometheus, Every Code, and Dexto for Claude Code CLI

set -e

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

# Configuration
INSTALL_DIR="$HOME/UnifiedAgents"
REPO_DIR="${REPO_DIR:-$(pwd)}"
CLAUDE_CONFIG_DIR="$HOME/.config/claude-code"

echo -e "${BLUE}================================================${NC}"
echo -e "${BLUE}   Unified Agent Integration Setup${NC}"
echo -e "${BLUE}   Prometheus + Every Code + Dexto${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""

# Create installation directory
echo -e "${YELLOW}[*] Creating installation directory...${NC}"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# Check prerequisites
echo -e "${YELLOW}[*] Checking prerequisites...${NC}"
command -v python3.11 >/dev/null 2>&1 || { echo -e "${RED}Python 3.11 required${NC}"; exit 1; }
command -v node >/dev/null 2>&1 || { echo -e "${RED}Node.js required${NC}"; exit 1; }
command -v cargo >/dev/null 2>&1 || { echo -e "${RED}Rust/Cargo required${NC}"; exit 1; }
command -v docker >/dev/null 2>&1 || { echo -e "${YELLOW}[!] Docker recommended for Prometheus${NC}"; }
echo -e "${GREEN}✓ Prerequisites met${NC}"
echo ""

# Clone repositories
echo -e "${YELLOW}[*] Cloning repositories...${NC}"

if [ ! -d "Prometheus" ]; then
    git clone https://github.com/EuniAI/Prometheus.git
    echo -e "${GREEN}✓ Prometheus cloned${NC}"
else
    echo -e "${YELLOW}  Prometheus already exists, skipping...${NC}"
fi

if [ ! -d "EveryCode" ]; then
    git clone https://github.com/just-every/code.git
    echo -e "${GREEN}✓ Every Code cloned${NC}"
else
    echo -e "${YELLOW}  Every Code already exists, skipping...${NC}"
fi

if [ ! -d "Dexto" ]; then
    git clone https://github.com/truffle-ai/dexto.git
    echo -e "${GREEN}✓ Dexto cloned${NC}"
else
    echo -e "${YELLOW}  Dexto already exists, skipping...${NC}"
fi
echo ""

# Setup Prometheus
echo -e "${YELLOW}[*] Setting up Prometheus...${NC}"
cd "$INSTALL_DIR/Prometheus"

# Create virtual environment
python3.11 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -q --upgrade pip
pip install -q -r requirements.txt

# Setup environment
if [ ! -f ".env" ]; then
    cp example.env .env
    echo -e "${YELLOW}  [!] Edit $INSTALL_DIR/Prometheus/.env with your API keys${NC}"
fi

# Start Neo4j (if Docker is available)
if command -v docker >/dev/null 2>&1; then
    docker-compose up -d neo4j 2>/dev/null || echo -e "${YELLOW}  [!] Neo4j start failed, may already be running${NC}"
    echo -e "${GREEN}✓ Neo4j starting${NC}"
fi

echo -e "${GREEN}✓ Prometheus installed${NC}"
echo ""

# Setup Every Code
echo -e "${YELLOW}[*] Setting up Every Code...${NC}"
cd "$INSTALL_DIR/EveryCode"

npm install -g @just-every/code 2>/dev/null || npm install -g @just-every/code

echo -e "${GREEN}✓ Every Code installed${NC}"
echo -e "${YELLOW}  [!] Run 'code' to authenticate with ChatGPT or set OPENAI_API_KEY${NC}"
echo ""

# Setup Dexto
echo -e "${YELLOW}[*] Setting up Dexto...${NC}"
cd "$INSTALL_DIR/Dexto"

npm install
npm run build

if [ ! -f "config.yaml" ]; then
    cp config.example.yaml config.yaml
    echo -e "${YELLOW}  [!] Edit $INSTALL_DIR/Dexto/config.yaml to configure Dexto${NC}"
fi

echo -e "${GREEN}✓ Dexto installed${NC}"
echo ""

# Build MCP servers
echo -e "${YELLOW}[*] Building MCP servers...${NC}"

# Prometheus MCP (Python)
cd "$INSTALL_DIR/Prometheus"
source venv/bin/activate
pip install -q mcp pydantic

# Every Code MCP (Python)
pip install -q mcp pydantic aiofiles httpx

# Dexto MCP (TypeScript)
cd "$INSTALL_DIR/Dexto"
npm install -g @modelcontextprotocol/sdk
npm install

echo -e "${GREEN}✓ MCP servers built${NC}"
echo ""

# Install Claude Code skills
echo -e "${YELLOW}[*] Installing Claude Code skills...${NC}"
mkdir -p "$CLAUDE_CONFIG_DIR/skills/agents"

# Copy skills
cat > "$CLAUDE_CONFIG_DIR/skills/agents/plan.md" << 'EOF'
# Agent: Plan

Generate implementation plans using Every Code's planning capabilities.

## Usage
/agent-plan "Implement user authentication with JWT"

## Backend
- Primary: Every Code (/plan command)
- Fallback: Prometheus (feature analysis)
EOF

cat > "$CLAUDE_CONFIG_DIR/skills/agents/fix-bug.md" << 'EOF'
# Agent: Fix Bug

End-to-end bug fixing with reproduction and verification.

## Usage
/agent-fix-bug "Login fails after password reset"

## Backend
- Primary: Prometheus (bug pipeline)
- Enhancement: Every Code Auto Review
EOF

cat > "$CLAUDE_CONFIG_DIR/skills/agents/solve.md" << 'EOF'
# Agent: Solve

Multi-agent problem solving with orchestration.

## Usage
/agent-solve "Optimize database queries for performance"

## Backend
- Primary: Every Code (/solve command)
- Support: Prometheus (context retrieval)
EOF

cat > "$CLAUDE_CONFIG_DIR/skills/agents/review.md" << 'EOF'
# Agent: Review

Background code review with quality checks.

## Usage
/agent-review

## Backend
- Primary: Every Code Auto Review
- Analysis: Prometheus (AST analysis)
EOF

cat > "$CLAUDE_CONFIG_DIR/skills/agents/context.md" << 'EOF'
# Agent: Context

Get semantic code context from knowledge graph.

## Usage
/agent-context "How does the authentication flow work?"

## Backend
- Primary: Prometheus (knowledge graph)
- Enhancement: Dexto (session context)
EOF

cat > "$CLAUDE_CONFIG_DIR/skills/agents/orchestrate.md" << 'EOF'
# Agent: Orchestrate

Orchestrate complex multi-agent workflows.

## Usage
/agent-orchestrate "Audit, fix, and test all authentication issues"

## Backend
- Primary: Dexto (orchestration)
- Support: Prometheus + Every Code
EOF

echo -e "${GREEN}✓ Claude Code skills installed${NC}"
echo ""

# Configure Claude Code MCP servers
echo -e "${YELLOW}[*] Configuring Claude Code MCP servers...${NC}"
mkdir -p "$CLAUDE_CONFIG_DIR"

MCP_CONFIG="$CLAUDE_CONFIG_DIR/config.json"
if [ -f "$MCP_CONFIG" ]; then
    # Backup existing config
    cp "$MCP_CONFIG" "$MCP_CONFIG.backup.$(date +%s)"
fi

# Create or update MCP config
cat > "$MCP_CONFIG" << EOF
{
  "mcpServers": {
    "prometheus": {
      "command": "python",
      "args": ["-m", "prometheus_mcp", "--repo", "$REPO_DIR"],
      "env": {
        "PROMETHEUS_REPO_PATH": "$REPO_DIR",
        "PYTHONPATH": "$INSTALL_DIR/Prometheus:\$PYTHONPATH"
      }
    },
    "everycode": {
      "command": "python",
      "args": ["-m", "everycode_mcp", "--repo", "$REPO_DIR"],
      "env": {
        "EVERYCODE_REPO_PATH": "$REPO_DIR",
        "PYTHONPATH": "$INSTALL_DIR/EveryCode:\$PYTHONPATH"
      }
    },
    "dexto": {
      "command": "node",
      "args": ["$INSTALL_DIR/Dexto/dist/cli.js", "--config", "$INSTALL_DIR/Dexto/config.yaml"],
      "env": {
        "DEXTO_PATH": "$INSTALL_DIR/Dexto"
      }
    }
  }
}
EOF

echo -e "${GREEN}✓ Claude Code configured${NC}"
echo ""

# Summary
echo -e "${BLUE}================================================${NC}"
echo -e "${GREEN}   Installation Complete!${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo ""
echo -e "1. ${YELLOW}Configure API keys:${NC}"
echo -e "   Edit: $INSTALL_DIR/Prometheus/.env"
echo -e "   Add: OPENAI_API_KEY or ANTHROPIC_API_KEY"
echo ""
echo -e "2. ${YELLOW}Authenticate Every Code:${NC}"
echo -e "   Run: code"
echo -e "   Choose: Sign in with ChatGPT"
echo ""
echo -e "3. ${YELLOW}Configure Dexto:${NC}"
echo -e "   Edit: $INSTALL_DIR/Dexto/config.yaml"
echo ""
echo -e "4. ${YELLOW}Build knowledge graph (optional, for Prometheus):${NC}"
echo -e "   cd $INSTALL_DIR/Prometheus"
echo -e "   source venv/bin/activate"
echo -e "   python -m prometheus.script.build_kg --repo_path $REPO_DIR"
echo ""
echo -e "5. ${YELLOW}Restart Claude Code${NC}"
echo ""
echo -e "${BLUE}Available Skills:${NC}"
echo -e "  /agent-plan       - Generate implementation plans"
echo -e "  /agent-fix-bug    - Fix bugs end-to-end"
echo -e "  /agent-solve      - Solve complex problems"
echo -e "  /agent-review     - Review code"
echo -e "  /agent-context    - Get code context"
echo -e "  /agent-orchestrate - Orchestrate workflows"
echo ""
echo -e "${BLUE}Installation Directory:${NC} $INSTALL_DIR"
echo -e "${BLUE}Repository Directory:${NC} $REPO_DIR"
echo ""
