#!/bin/bash

# DCD Setup Script
# Installs DCD (Duplicate Code Detector) - Open Source Alternative to Simian
# License: AGPL-3.0 (much more permissive than Simian!)

set -e  # Exit on any error

# 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} DCD Setup Script${NC}"
    echo -e "${BLUE} Open Source Duplicate Code Detector${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"
}

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

check_go() {
    if ! command -v go &> /dev/null; then
        print_error "Go is not installed or not in PATH"
        echo "Please install Go 1.19+ from: https://golang.org/dl/"
        echo "Then run this script again."
        exit 1
    fi
    
    local go_version=$(go version | grep -o 'go[0-9]\+\.[0-9]\+' | sed 's/go//')
    print_step "Found Go version: $go_version"
}

install_dcd() {
    print_step "Installing DCD via Go..."
    
    if go install github.com/boyter/dcd@latest; then
        print_success "DCD installed successfully!"
    else
        print_error "Failed to install DCD"
        echo "This might be due to network issues or Go configuration."
        echo "Try running manually: go install github.com/boyter/dcd@latest"
        exit 1
    fi
}

verify_installation() {
    print_step "Verifying DCD installation..."
    
    if command -v dcd &> /dev/null; then
        local dcd_version=$(dcd --version 2>&1 | head -n1)
        print_success "DCD is available: $dcd_version"
        return 0
    else
        print_warning "DCD not found in PATH"
        echo
        echo "You may need to add Go's bin directory to your PATH:"
        echo "  export PATH=\$PATH:\$(go env GOPATH)/bin"
        echo
        echo "Or add this to your shell profile (~/.bashrc, ~/.zshrc, etc.)"
        return 1
    fi
}

test_dcd() {
    print_step "Testing DCD with sample code..."
    
    # Create a temporary test file
    local test_dir=$(mktemp -d)
    local test_file1="$test_dir/test1.js"
    local test_file2="$test_dir/test2.js"
    
    # Create test files with duplicate code
    cat > "$test_file1" << 'EOF'
function processData(data) {
    if (!data) {
        console.log('No data provided');
        return null;
    }
    return data.map(item => item.value);
}
EOF
    
    cat > "$test_file2" << 'EOF'
function handleData(data) {
    if (!data) {
        console.log('No data provided');
        return null;
    }
    return data.filter(item => item.active);
}
EOF
    
    echo "Running: dcd --match-length 3 $test_dir"
    if dcd --match-length 3 "$test_dir" 2>/dev/null; then
        print_success "DCD test completed!"
    else
        print_warning "DCD test had no output (this might be normal if no duplicates found)"
    fi
    
    # Cleanup
    rm -rf "$test_dir"
}

show_usage() {
    echo
    print_step "DCD Usage Examples:"
    echo
    echo "# Basic analysis"
    echo "dcd src/"
    echo
    echo "# With specific match length"
    echo "dcd --match-length 10 src/"
    echo
    echo "# Include specific file types"
    echo "dcd --include-ext js,ts,jsx src/"
    echo
    echo "# Exclude patterns"
    echo "dcd --exclude-pattern node_modules,dist src/"
    echo
    echo "# Fuzzy matching (allows minor differences)"
    echo "dcd --fuzz 10 src/"
    echo
    echo "# Verbose output"
    echo "dcd --verbose src/"
    echo
}

show_next_steps() {
    echo
    print_step "Next Steps:"
    echo
    echo "1. Test the MCP server with DCD:"
    echo "   npm test"
    echo
    echo "2. Try DCD directly on your code:"
    echo "   dcd test-code/"
    echo
    echo "3. Update Cursor configuration to use DCD tools:"
    echo "   - Use 'analyze_duplicates_dcd' instead of 'analyze_duplicates'"
    echo "   - Use 'scan_repository_dcd' for full repo analysis"
    echo
    echo "4. Check DCD plugin status:"
    echo "   # In Cursor, ask: 'What is the status of the DCD plugin?'"
    echo
}

main() {
    print_header
    
    print_step "This script will install DCD (Duplicate Code Detector)"
    echo "DCD is an open source alternative to Simian with AGPL-3.0 license"
    echo "Repository: https://github.com/boyter/dcd"
    echo
    
    check_go
    install_dcd
    
    if verify_installation; then
        test_dcd
        show_usage
        show_next_steps
        
        echo
        print_success "DCD setup complete! 🎉"
        echo
        print_step "DCD is:"
        echo "✅ Open source (AGPL-3.0 license)"
        echo "✅ Free for commercial use"
        echo
    else
        print_warning "DCD installation completed but PATH setup may be needed"
        echo "Please add Go's bin directory to your PATH and try again"
    fi
}

# Only run if this file is executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi 