#!/bin/bash

# Simian MCP Setup Script
# Downloads and configures Simian Similarity Analyzer for the MCP server

set -e  # Exit on any error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
SIMIAN_DIR="$PROJECT_ROOT/tools/simian"
SIMIAN_VERSION="4.0.0"

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

print_header() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE} Simian MCP Setup Script${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo
}

print_step() {
    echo -e "${GREEN}[STEP]${NC} $1"
}

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

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

check_java() {
    print_step "Checking Java installation..."
    
    if command -v java >/dev/null 2>&1; then
        JAVA_VERSION=$(java -version 2>&1 | head -n1 | cut -d'"' -f2)
        echo "✓ Java found: $JAVA_VERSION"
        
        # Check if it's Java 8 or higher (Simian requires Java 1.4+, but let's be modern)
        JAVA_MAJOR=$(echo "$JAVA_VERSION" | cut -d'.' -f1)
        if [ "$JAVA_MAJOR" -ge 8 ] 2>/dev/null; then
            echo "✓ Java version is compatible"
        else
            print_warning "Java version might be too old. Simian requires Java 1.4+, but Java 8+ recommended."
        fi
    else
        print_error "Java not found. Please install Java 8+ and try again."
        echo "On Ubuntu/Debian: sudo apt install default-jdk"
        echo "On macOS: brew install openjdk"
        exit 1
    fi
    echo
}

create_directories() {
    print_step "Creating directories..."
    mkdir -p "$SIMIAN_DIR"
    mkdir -p "$PROJECT_ROOT/cache"
    mkdir -p "$PROJECT_ROOT/temp"
    echo "✓ Directories created"
    echo
}

show_license_info() {
    print_step "Simian Licensing Information"
    echo
    echo "Simian Similarity Analyzer requires a license agreement."
    echo "There are two licensing options:"
    echo
    echo "1. ${GREEN}Academic License${NC} - Free for educational/research use"
    echo "2. ${YELLOW}Commercial License${NC} - Paid license for commercial use"
    echo
    echo "License terms summary:"
    echo "• Academic: Free for research/education, must acknowledge in publications"
    echo "• Commercial: Contact vendor for pricing"
    echo
    echo "For this MCP development project, academic license should be sufficient."
    echo
}

download_simian() {
    print_step "Downloading Simian..."
    
    # Check if already downloaded
    if [ -f "$SIMIAN_DIR/simian-${SIMIAN_VERSION}.jar" ]; then
        echo "✓ Simian already downloaded"
        return 0
    fi
    
    echo "Due to licensing requirements, Simian must be downloaded manually."
    echo
    echo "Please follow these steps:"
    echo "1. Visit: https://simian.quandarypeak.com/download/"
    echo "2. Select 'Academic License' (for this project)"
    echo "3. Read and accept the license terms"
    echo "4. Download the JAR file"
    echo "5. Move the downloaded file to: $SIMIAN_DIR/"
    echo
    echo "Expected filename: simian-${SIMIAN_VERSION}.jar"
    echo
    
    # Try to find alternative sources
    print_warning "Alternative: Trying to download older version from FreeBSD mirrors..."
    
    # Try FreeBSD ports version (2.5.10) as fallback
    FREEBSD_URL="https://distfiles.freebsd.org/distfiles/simian-2.5.10.tar.gz"
    FALLBACK_FILE="$SIMIAN_DIR/simian-2.5.10.tar.gz"
    
    if command -v curl >/dev/null 2>&1; then
        if curl -L -o "$FALLBACK_FILE" "$FREEBSD_URL" 2>/dev/null; then
            echo "✓ Downloaded Simian 2.5.10 (fallback version)"
            cd "$SIMIAN_DIR"
            tar -xzf "simian-2.5.10.tar.gz"
            if [ -f "simian-2.5.10/bin/simian-2.5.10.jar" ]; then
                cp "simian-2.5.10/bin/simian-2.5.10.jar" "./simian.jar"
                echo "✓ Extracted Simian JAR file"
                return 0
            fi
        fi
    fi
    
    echo
    print_error "Could not automatically download Simian."
    echo "Please download manually from the official site."
    return 1
}

create_wrapper_script() {
    print_step "Creating Simian wrapper script..."
    
    WRAPPER_SCRIPT="$SIMIAN_DIR/simian"
    
    cat > "$WRAPPER_SCRIPT" << 'EOF'
#!/bin/bash

# Simian Wrapper Script for MCP
# Automatically detects the correct JAR file and runs Simian

SIMIAN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Find the Simian JAR file
SIMIAN_JAR=""
if [ -f "$SIMIAN_DIR/simian-4.0.0.jar" ]; then
    SIMIAN_JAR="$SIMIAN_DIR/simian-4.0.0.jar"
elif [ -f "$SIMIAN_DIR/simian.jar" ]; then
    SIMIAN_JAR="$SIMIAN_DIR/simian.jar"
elif [ -f "$SIMIAN_DIR/simian-2.5.10.jar" ]; then
    SIMIAN_JAR="$SIMIAN_DIR/simian-2.5.10.jar"
else
    echo "Error: Simian JAR file not found in $SIMIAN_DIR"
    echo "Expected one of: simian-4.0.0.jar, simian.jar, simian-2.5.10.jar"
    exit 1
fi

# Check if Java is available
if ! command -v java >/dev/null 2>&1; then
    echo "Error: Java not found. Please install Java and try again."
    exit 1
fi

# Run Simian with all provided arguments
java -jar "$SIMIAN_JAR" "$@"
EOF

    chmod +x "$WRAPPER_SCRIPT"
    echo "✓ Wrapper script created at: $WRAPPER_SCRIPT"
    echo
}

test_simian() {
    print_step "Testing Simian installation..."
    
    WRAPPER_SCRIPT="$SIMIAN_DIR/simian"
    
    if [ -x "$WRAPPER_SCRIPT" ]; then
        echo "Testing Simian version check..."
        if "$WRAPPER_SCRIPT" -version 2>/dev/null; then
            echo "✓ Simian is working correctly"
        else
            # Try without -version flag (some versions might not support it)
            if "$WRAPPER_SCRIPT" 2>/dev/null | head -n 5; then
                echo "✓ Simian is working"
            else
                print_warning "Simian might not be working correctly"
                echo "You can test manually with: $WRAPPER_SCRIPT"
            fi
        fi
    else
        print_error "Wrapper script not found or not executable"
        return 1
    fi
    echo
}

create_test_files() {
    print_step "Creating test files for Simian..."
    
    TEST_DIR="$PROJECT_ROOT/test-code"
    mkdir -p "$TEST_DIR"
    
    # Create some sample code with intentional duplication
    cat > "$TEST_DIR/example1.js" << 'EOF'
function calculateTotal(items) {
    let total = 0;
    for (let i = 0; i < items.length; i++) {
        total += items[i].price * items[i].quantity;
    }
    return total;
}

function calculateSubtotal(products) {
    let total = 0;
    for (let i = 0; i < products.length; i++) {
        total += products[i].price * products[i].quantity;
    }
    return total;
}
EOF

    cat > "$TEST_DIR/example2.js" << 'EOF'
class OrderProcessor {
    processOrder(order) {
        // Validate order
        if (!order.items || order.items.length === 0) {
            throw new Error('Order must contain items');
        }
        
        // Calculate total
        let total = 0;
        for (let i = 0; i < order.items.length; i++) {
            total += order.items[i].price * order.items[i].quantity;
        }
        
        return { total, status: 'processed' };
    }
}
EOF

    echo "✓ Test files created in: $TEST_DIR"
    echo
}

run_test_analysis() {
    print_step "Running test analysis..."
    
    WRAPPER_SCRIPT="$SIMIAN_DIR/simian"
    TEST_DIR="$PROJECT_ROOT/test-code"
    
    if [ -x "$WRAPPER_SCRIPT" ] && [ -d "$TEST_DIR" ]; then
        echo "Analyzing test files for duplicates..."
        echo "Command: $WRAPPER_SCRIPT -threshold=3 \"$TEST_DIR/*.js\""
        echo
        
        if "$WRAPPER_SCRIPT" -threshold=3 "$TEST_DIR"/*.js 2>/dev/null; then
            echo
            echo "✓ Test analysis complete!"
            echo "You should see duplicate code detection results above."
        else
            print_warning "Test analysis failed, but Simian might still work"
            echo "Try running manually: $WRAPPER_SCRIPT -threshold=3 \"$TEST_DIR/*.js\""
        fi
    else
        print_warning "Skipping test analysis (Simian or test files not available)"
    fi
    echo
}

show_usage_examples() {
    print_step "Usage Examples"
    
    WRAPPER_SCRIPT="$SIMIAN_DIR/simian"
    
    echo "Basic usage:"
    echo "  $WRAPPER_SCRIPT -threshold=6 \"**/*.js\""
    echo "  $WRAPPER_SCRIPT -threshold=3 \"src/**/*.java\""
    echo "  $WRAPPER_SCRIPT -formatter=xml \"**/*.py\""
    echo
    echo "For MCP integration:"
    echo "  $WRAPPER_SCRIPT -formatter=xml -threshold=4 /path/to/code"
    echo
    echo "Common options:"
    echo "  -threshold=N        Minimum lines for duplication (default: 6)"
    echo "  -formatter=xml      Output in XML format (better for parsing)"
    echo "  -formatter=plain    Human-readable output"
    echo "  -ignoreStrings      Ignore string literals"
    echo "  -ignoreNumbers      Ignore numeric literals"
    echo
}

create_config() {
    print_step "Creating MCP configuration..."
    
    CONFIG_FILE="$PROJECT_ROOT/config/simian.json"
    mkdir -p "$PROJECT_ROOT/config"
    
    cat > "$CONFIG_FILE" << EOF
{
  "simian": {
    "executable": "$SIMIAN_DIR/simian",
    "defaultThreshold": 6,
    "defaultFormatter": "xml",
    "timeout": 30000,
    "cache": {
      "enabled": true,
      "directory": "$PROJECT_ROOT/cache",
      "ttl": 3600
    },
    "supportedExtensions": [
      ".js", ".ts", ".java", ".c", ".cpp", ".cs", ".py", ".rb", ".php", ".html", ".xml", ".css"
    ]
  }
}
EOF

    echo "✓ Configuration created at: $CONFIG_FILE"
    echo
}

main() {
    print_header
    
    show_license_info
    echo
    read -p "Do you understand and accept the licensing terms? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Setup cancelled. You must accept the license terms to use Simian."
        exit 1
    fi
    echo
    
    check_java
    create_directories
    
    if download_simian; then
        create_wrapper_script
        test_simian
        create_test_files
        run_test_analysis
        create_config
        show_usage_examples
        
        echo -e "${GREEN}========================================${NC}"
        echo -e "${GREEN} Simian Setup Complete!${NC}"
        echo -e "${GREEN}========================================${NC}"
        echo
        echo "Next steps for MCP development:"
        echo "1. Initialize Node.js project: npm init"
        echo "2. Install MCP SDK: npm install @modelcontextprotocol/sdk"
        echo "3. Start implementing the MCP server"
        echo
        echo "Simian is ready at: $SIMIAN_DIR/simian"
        echo "Configuration: $PROJECT_ROOT/config/simian.json"
        echo
    else
        print_error "Simian setup failed. Please download manually and re-run this script."
        exit 1
    fi
}

# Run main function
main "$@" 