#!/bin/bash

# Matrix Pattern MCP Server Setup Script
# This script initializes the Matrix Pattern System environment

set -e

echo "🔷 Matrix Pattern MCP Server Setup"
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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check Node.js version
print_status "Checking Node.js version..."
if ! command -v node &> /dev/null; then
    print_error "Node.js is not installed. Please install Node.js 18+ and try again."
    exit 1
fi

NODE_VERSION=$(node -v | cut -d 'v' -f 2)
REQUIRED_VERSION="18.0.0"

if ! npx semver -r ">=$REQUIRED_VERSION" "$NODE_VERSION" &> /dev/null; then
    print_error "Node.js version $NODE_VERSION is not supported. Please install Node.js $REQUIRED_VERSION or higher."
    exit 1
fi

print_success "Node.js version $NODE_VERSION is compatible"

# Check if npm is available
print_status "Checking npm availability..."
if ! command -v npm &> /dev/null; then
    print_error "npm is not available. Please install npm and try again."
    exit 1
fi
print_success "npm is available"

# Create necessary directories if they don't exist
print_status "Creating directory structure..."
mkdir -p .matrix_pattern/logs
mkdir -p .matrix_pattern/backups
mkdir -p .matrix_pattern/temp
mkdir -p src/handlers
mkdir -p src/utils
mkdir -p src/validators
mkdir -p src/test/fixtures

print_success "Directory structure created"

# Install dependencies
print_status "Installing dependencies..."
if [ -f "package-lock.json" ]; then
    npm ci
else
    npm install
fi
print_success "Dependencies installed"

# Initialize Matrix Pattern configuration
print_status "Initializing Matrix Pattern configuration..."
if [ ! -f ".matrix_pattern/config.json" ]; then
    print_warning "Configuration file not found. Using default configuration."
fi

# Update configuration with initialization timestamp
node -e "
const fs = require('fs');
const config = JSON.parse(fs.readFileSync('.matrix_pattern/config.json', 'utf8'));
config.matrix_pattern.initialized = true;
config.matrix_pattern.initialized_at = new Date().toISOString();
fs.writeFileSync('.matrix_pattern/config.json', JSON.stringify(config, null, 2));
console.log('Configuration updated with initialization timestamp');
"

print_success "Matrix Pattern configuration initialized"

# Create .gitignore if it doesn't exist
if [ ! -f ".gitignore" ]; then
    print_status "Creating .gitignore file..."
    cat > .gitignore << 'EOL'
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Coverage directory used by tools like istanbul
coverage/

# nyc test coverage
.nyc_output

# Logs
logs
*.log

# Runtime and temp files
.matrix_pattern/logs/
.matrix_pattern/temp/
.matrix_pattern/backups/

# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

# IDE files
.vscode/
.idea/
*.swp
*.swo

# Build outputs
dist/
build/
*.tsbuildinfo

# Test outputs
test-results/
EOL
    print_success ".gitignore file created"
fi

# Validate setup
print_status "Validating setup..."

# Check if all required directories exist
REQUIRED_DIRS=(
    ".matrix_pattern/matrix"
    ".matrix_pattern/metadata"
    ".matrix_pattern/metadata/horizontals"
    ".matrix_pattern/metadata/sync-reports/horizontal"
    ".matrix_pattern/metadata/sync-reports/vertical"
    "src"
    "src/test"
)

for dir in "${REQUIRED_DIRS[@]}"; do
    if [ ! -d "$dir" ]; then
        print_error "Required directory $dir is missing"
        exit 1
    fi
done

print_success "All required directories are present"

# Check if config file is valid JSON
if ! node -e "JSON.parse(require('fs').readFileSync('.matrix_pattern/config.json', 'utf8'))" 2>/dev/null; then
    print_error "Configuration file is not valid JSON"
    exit 1
fi

print_success "Configuration file is valid"

echo ""
echo "🎉 Matrix Pattern MCP Server setup completed successfully!"
echo ""
echo "Next steps:"
echo "1. Run 'npm start' to start the MCP server"
echo "2. Run 'npm test' to run the test suite"
echo "3. Run 'npm run init-matrix' to initialize pattern management"
echo ""
echo "For more information, check the documentation or run 'npm run --silent' to see available scripts."