#!/bin/bash

# Claude Session Intelligence Setup Script
# Installs and configures intelligent session management for NX workspaces

set -e

echo "🧠 Claude Session Intelligence Setup"
echo "=================================="
echo ""

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

# Check if we're in an NX workspace
if [ ! -f "nx.json" ]; then
    echo -e "${RED}❌ Not an NX workspace${NC}"
    echo "Please run this script from the root of an NX workspace"
    exit 1
fi

echo -e "${BLUE}📋 Found NX workspace${NC}"
echo ""

# Install the plugin
echo -e "${BLUE}📦 Installing @nx-conductor/claude-sessions plugin...${NC}"
if command -v pnpm &> /dev/null; then
    pnpm add -D @nx-conductor/claude-sessions
elif command -v yarn &> /dev/null; then
    yarn add -D @nx-conductor/claude-sessions
else
    npm install -D @nx-conductor/claude-sessions
fi

echo -e "${GREEN}✅ Plugin installed${NC}"
echo ""

# Install MCP server globally
echo -e "${BLUE}🌐 Installing @nx-conductor/mcp-server globally...${NC}"
if command -v pnpm &> /dev/null; then
    pnpm add -g @nx-conductor/mcp-server
elif command -v yarn &> /dev/null; then
    yarn global add @nx-conductor/mcp-server
else
    npm install -g @nx-conductor/mcp-server
fi

echo -e "${GREEN}✅ MCP server installed${NC}"
echo ""

# Initialize the plugin  
echo -e "${BLUE}🚀 Initializing intelligent session management...${NC}"
npx nx g @nx-conductor/claude-sessions:init --maxConcurrency=5 --sessionTimeout=30m

echo -e "${GREEN}✅ Plugin initialized${NC}"
echo ""

# Create .claude directories for existing libraries
echo -e "${BLUE}📁 Setting up .claude directories for libraries...${NC}"
LIBS_DIR="libs"
if [ -d "$LIBS_DIR" ]; then
    for lib in "$LIBS_DIR"/*; do
        if [ -d "$lib" ]; then
            lib_name=$(basename "$lib")
            claude_dir="$lib/.claude"
            
            if [ ! -d "$claude_dir" ]; then
                mkdir -p "$claude_dir"
                
                # Create initial context.md
                cat > "$claude_dir/context.md" << EOF
# $lib_name Library Context

## Purpose
[Describe what this library does]

## Architecture
[Key architectural patterns and design decisions]

## Dependencies
- [List key dependencies and their purposes]

## Established Patterns
- [Document coding conventions and patterns]

## Integration Points
- [How this library integrates with others]

## Known Issues & Solutions
- [Common problems and their solutions]

## Testing Strategy
- [How this library should be tested]
EOF

                # Create empty JSON files
                echo '{"decisions": []}' > "$claude_dir/decisions.json"
                echo '{"patterns": []}' > "$claude_dir/patterns.json"
                echo '{"sessions": []}' > "$claude_dir/session-history.json"
                echo '{}' > "$claude_dir/dependencies.json"
                
                # Create metadata
                cat > "$claude_dir/meta.json" << EOF
{
  "library_name": "$lib_name",
  "intelligence_version": "1.0.0",
  "created": "$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")",
  "last_updated": "$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")",
  "session_count": 0,
  "decision_count": 0,
  "pattern_count": 0,
  "maturity_level": "experimental",
  "expertise_areas": [],
  "complexity_metrics": {
    "files_managed": 0,
    "dependency_depth": 0,
    "pattern_reuse": 0.0
  }
}
EOF

                echo -e "  ${GREEN}✅ Created intelligence directory for $lib_name${NC}"
            else
                echo -e "  ${YELLOW}⚠️ Intelligence directory already exists for $lib_name${NC}"
            fi
        fi
    done
else
    echo -e "${YELLOW}⚠️ No libs directory found${NC}"
fi

echo ""

# Configure MCP server for Claude Desktop
echo -e "${BLUE}⚙️ Configuring MCP server...${NC}"
CLAUDE_CONFIG_DIR="$HOME/.config/Claude"
CLAUDE_CONFIG_FILE="$CLAUDE_CONFIG_DIR/claude_desktop_config.json"

# Create config directory if it doesn't exist
mkdir -p "$CLAUDE_CONFIG_DIR"

# Get current workspace path
WORKSPACE_ROOT=$(pwd)

# Create or update Claude Desktop config
if [ -f "$CLAUDE_CONFIG_FILE" ]; then
    echo -e "${YELLOW}⚠️ Existing Claude Desktop config found${NC}"
    echo "Please manually add the following to your $CLAUDE_CONFIG_FILE:"
    echo ""
    echo -e "${BLUE}{"
    echo '  "mcpServers": {'
    echo '    "claude-session-intelligence": {'
    echo '      "command": "npx",'
    echo '      "args": ["claude-session-intelligence-mcp"],'
    echo '      "env": {'
    echo "        \"WORKSPACE_ROOT\": \"$WORKSPACE_ROOT\""
    echo '      }'
    echo '    }'
    echo '  }'
    echo -e "}${NC}"
else
    cat > "$CLAUDE_CONFIG_FILE" << EOF
{
  "mcpServers": {
    "nx-conductor-intelligence": {
      "command": "npx",
      "args": ["@nx-conductor/mcp-server"],
      "env": {
        "WORKSPACE_ROOT": "$WORKSPACE_ROOT"
      }
    }
  }
}
EOF
    echo -e "${GREEN}✅ Claude Desktop configured${NC}"
fi

echo ""

# Create .gitignore entries
echo -e "${BLUE}📝 Updating .gitignore...${NC}"
if [ ! -f ".gitignore" ]; then
    touch ".gitignore"
fi

# Add session-specific ignores
if ! grep -q ".nx-claude-sessions/active" ".gitignore"; then
    echo "" >> ".gitignore"
    echo "# Claude Session Intelligence" >> ".gitignore"
    echo ".nx-claude-sessions/active/" >> ".gitignore"
    echo ".nx-claude-sessions/coordination/" >> ".gitignore"
    echo -e "${GREEN}✅ Updated .gitignore${NC}"
else
    echo -e "${YELLOW}⚠️ .gitignore already configured${NC}"
fi

echo ""
echo -e "${GREEN}🎉 Setup Complete!${NC}"
echo ""
echo -e "${BLUE}Next Steps:${NC}"
echo "1. Restart Claude Desktop to load the MCP server"
echo "2. Edit the context.md files in each library's .claude/ directory"
echo "3. Start your first intelligent session:"
echo ""
echo -e "${YELLOW}   npx nx start-claude-session <library-name> --task=\"Your development task\"${NC}"
echo ""
echo "4. Try these commands in any Claude Code session:"
echo -e "${YELLOW}   Load context for my auth library${NC}"
echo -e "${YELLOW}   What decisions have been made about authentication?${NC}"
echo -e "${YELLOW}   Show me patterns I can reuse${NC}"
echo ""
echo -e "${BLUE}🧠 Every session will now build on accumulated knowledge!${NC}"

# Check for common issues
echo ""
echo -e "${BLUE}🔍 System Check:${NC}"

# Check Node version
NODE_VERSION=$(node --version)
echo "Node.js: $NODE_VERSION"

# Check if Claude Code is installed
if command -v claude-code &> /dev/null; then
    echo -e "${GREEN}✅ Claude Code CLI found${NC}"
else
    echo -e "${YELLOW}⚠️ Claude Code CLI not found in PATH${NC}"
    echo "   Install Claude Code CLI for full functionality"
fi

# Check if Claude Desktop is running
if pgrep -f "Claude" > /dev/null; then
    echo -e "${YELLOW}⚠️ Claude Desktop is running${NC}"
    echo "   Please restart Claude Desktop to load the MCP server"
else
    echo -e "${GREEN}✅ Ready to start Claude Desktop${NC}"
fi

echo ""
echo -e "${GREEN}Setup completed successfully! 🚀${NC}"