#!/bin/bash

# Graphorama MCP Doctor - Simple Installation Health Check
# Lightweight verification without external dependencies

set -euo pipefail

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

# Counters
CHECKS_PASSED=0
CHECKS_FAILED=0
WARNINGS=0

# Configuration
BINARY_NAME="graphorama"

# Print functions
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[✅ PASS]${NC} $1"; ((CHECKS_PASSED++)); }
print_warning() { echo -e "${YELLOW}[⚠️  WARN]${NC} $1"; ((WARNINGS++)); }
print_error() { echo -e "${RED}[❌ FAIL]${NC} $1"; ((CHECKS_FAILED++)); }
print_bold() { echo -e "${BOLD}$1${NC}"; }

# Header
print_header() {
    echo
    print_bold "🩺 Graphorama MCP Doctor"
    echo "   Quick health check for your installation"
    echo
}

# Find binary in common locations
find_binary() {
    # Check PATH first
    if command -v "$BINARY_NAME" >/dev/null 2>&1; then
        command -v "$BINARY_NAME"
        return 0
    fi
    
    # Check common locations
    local locations=(
        "/usr/local/bin/$BINARY_NAME"
        "/usr/bin/$BINARY_NAME"
        "$HOME/bin/$BINARY_NAME"  
        "$HOME/.local/bin/$BINARY_NAME"
        "./target/release/$BINARY_NAME"
        "./$BINARY_NAME"
    )
    
    for location in "${locations[@]}"; do
        if [[ -f "$location" ]]; then
            echo "$location"
            return 0
        fi
    done
    
    return 1
}

# Test binary installation
test_binary() {
    print_bold "🔍 Binary Installation"
    
    local binary_path
    if binary_path=$(find_binary); then
        print_success "Binary found: $binary_path"
    else
        print_error "Binary not found in PATH or common locations"
        return 1
    fi
    
    # Test executable
    if [[ -x "$binary_path" ]]; then
        print_success "Binary is executable"
    else
        print_error "Binary is not executable"
        print_info "Fix with: chmod +x $binary_path"
        return 1
    fi
    
    # Test version
    if "$binary_path" --version >/dev/null 2>&1; then
        local version
        version=$("$binary_path" --version)
        print_success "Version: $version"
    else
        print_error "Cannot get version information"
    fi
    
    # Test help
    if "$binary_path" --help >/dev/null 2>&1; then
        print_success "Help command works"
    else
        print_warning "Help command failed"
    fi
    
    echo "$binary_path"
}

# Test MCP functionality (basic)
test_mcp() {
    local binary_path="$1"
    
    print_bold "🔌 MCP Protocol"
    
    # Test basic MCP startup (just check if it accepts stdio transport)
    if "$binary_path" serve --help 2>&1 | grep -q "transport"; then
        print_success "MCP serve command available"
    else
        print_error "MCP serve command not working"
    fi
    
    # Quick MCP test with timeout simulation
    local mcp_test_result=0
    {
        echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | "$binary_path" serve --transport stdio 2>/dev/null &
        local pid=$!
        sleep 3
        if kill $pid 2>/dev/null; then
            wait $pid 2>/dev/null || true
        fi
        mcp_test_result=0
    } || mcp_test_result=1
    
    if [[ $mcp_test_result -eq 0 ]]; then
        print_success "Basic MCP protocol test passed"
    else
        print_warning "MCP protocol test inconclusive"
    fi
}

# Test MCP clients
test_clients() {
    print_bold "🖥️  MCP Client Detection"
    
    local found_any=false
    
    # Claude Desktop
    if [[ -d "$HOME/Library/Application Support/Claude" ]] || [[ -d "$HOME/.config/Claude" ]] || [[ -d "$HOME/AppData/Roaming/Claude" ]]; then
        found_any=true
        local config_files=(
            "$HOME/Library/Application Support/Claude/claude_desktop_config.json"
            "$HOME/.config/Claude/claude_desktop_config.json"
            "$HOME/AppData/Roaming/Claude/claude_desktop_config.json"
        )
        
        local configured=false
        for config in "${config_files[@]}"; do
            if [[ -f "$config" ]] && grep -q "graphorama" "$config" 2>/dev/null; then
                configured=true
                break
            fi
        done
        
        if [[ "$configured" == true ]]; then
            print_success "Claude Desktop configured"
        else
            print_warning "Claude Desktop detected but not configured"
        fi
    fi
    
    # Claude Code  
    if command -v claude >/dev/null 2>&1; then
        found_any=true
        if claude mcp list 2>/dev/null | grep -q "graphorama"; then
            print_success "Claude Code configured"
        else
            print_warning "Claude Code detected but not configured"
        fi
    fi
    
    # Cursor IDE
    if [[ -d "$HOME/.cursor" ]] || command -v cursor >/dev/null 2>&1; then
        found_any=true
        if [[ -f "$HOME/.cursor/mcp.json" ]] && grep -q "graphorama" "$HOME/.cursor/mcp.json" 2>/dev/null; then
            print_success "Cursor IDE configured"
        else
            print_warning "Cursor IDE detected but not configured"
        fi
    fi
    
    # Windsurf IDE
    if [[ -d "$HOME/.codeium/windsurf" ]] || command -v windsurf >/dev/null 2>&1; then
        found_any=true
        if [[ -f "$HOME/.codeium/windsurf/mcp_config.json" ]] && grep -q "graphorama" "$HOME/.codeium/windsurf/mcp_config.json" 2>/dev/null; then
            print_success "Windsurf IDE configured"
        else
            print_warning "Windsurf IDE detected but not configured"
        fi
    fi
    
    # Gemini CLI
    if command -v gemini >/dev/null 2>&1; then
        found_any=true
        local gemini_config=""
        for config in "$HOME/.config/gemini-cli/settings.json" "$HOME/AppData/Roaming/gemini-cli/settings.json"; do
            if [[ -f "$config" ]]; then
                gemini_config="$config"
                break
            fi
        done
        
        if [[ -n "$gemini_config" ]] && grep -q "graphorama" "$gemini_config" 2>/dev/null; then
            print_success "Gemini CLI configured"
        else
            print_warning "Gemini CLI detected but not configured"
        fi
    fi
    
    if [[ "$found_any" == false ]]; then
        print_warning "No MCP clients detected"
    fi
}

# Test environment
test_environment() {
    print_bold "🌍 Environment"
    
    # Check PATH
    if echo "$PATH" | grep -q "/usr/local/bin"; then
        print_success "PATH includes /usr/local/bin"
    else
        print_warning "PATH does not include /usr/local/bin"
    fi
    
    # Check permissions
    if [[ -w "/usr/local/bin" ]] || [[ -w "$HOME/bin" ]] || [[ -w "$HOME/.local/bin" ]]; then
        print_success "Have write access to common binary directories"
    else
        print_warning "May need sudo for binary installation"
    fi
    
    # Check shell
    if [[ -n "${SHELL:-}" ]]; then
        print_success "Shell: $SHELL"
    else
        print_warning "Shell not detected"
    fi
    
    # Check OS
    local os_info=""
    if command -v uname >/dev/null 2>&1; then
        os_info=$(uname -s 2>/dev/null || echo "Unknown")
        print_success "OS: $os_info"
    fi
}

# Show recommendations
show_recommendations() {
    echo
    print_bold "💡 Recommendations"
    
    if [[ $CHECKS_FAILED -gt 0 ]]; then
        echo "❌ Critical issues found:"
        
        if ! find_binary >/dev/null 2>&1; then
            echo "   • Install graphorama binary:"
            echo "     curl -fsSL https://raw.githubusercontent.com/nedops/grapharoma-mcp/main/install.sh | bash"
        fi
        
        echo "   • Check installation guide: https://github.com/nedops/grapharoma-mcp"
    fi
    
    if [[ $WARNINGS -gt 0 ]]; then
        echo "⚠️  Improvements available:"
        echo "   • Configure detected MCP clients"
        echo "   • Run setup scripts from: ~/.graphorama/wrappers/"
        echo "   • See quick-start guides: https://github.com/nedops/grapharoma-mcp/tree/main/docs/quick-start"
    fi
    
    if [[ $CHECKS_FAILED -eq 0 && $WARNINGS -eq 0 ]]; then
        echo "🎉 Everything looks perfect!"
        echo "   • Test with: 'Can you validate this code for me?'"
        echo "   • Check examples: https://github.com/nedops/grapharoma-mcp/tree/main/examples"
    fi
}

# Show final results
show_results() {
    echo
    print_bold "📊 Health Check Summary"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    if [[ $CHECKS_PASSED -gt 0 ]]; then
        echo -e "${GREEN}✅ Checks Passed: $CHECKS_PASSED${NC}"
    fi
    
    if [[ $CHECKS_FAILED -gt 0 ]]; then
        echo -e "${RED}❌ Checks Failed: $CHECKS_FAILED${NC}"
    fi
    
    if [[ $WARNINGS -gt 0 ]]; then
        echo -e "${YELLOW}⚠️  Warnings: $WARNINGS${NC}"
    fi
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Overall status
    if [[ $CHECKS_FAILED -eq 0 ]]; then
        if [[ $WARNINGS -eq 0 ]]; then
            print_bold "🎉 PERFECT! Graphorama is ready to use."
        else
            print_bold "✅ GOOD! Minor issues that can be improved."
        fi
    else
        print_bold "❌ ISSUES found that need attention."
    fi
}

# Main function
main() {
    print_header
    
    # Run checks
    local binary_path=""
    if binary_path=$(test_binary); then
        test_mcp "$binary_path"
    fi
    
    test_clients
    test_environment
    
    # Show results
    show_results
    show_recommendations
    
    echo
    
    # Exit with appropriate code
    if [[ $CHECKS_FAILED -gt 0 ]]; then
        exit 1
    else
        exit 0
    fi
}

# Usage
if [[ "${1:-}" == "--help" ]] || [[ "${1:-}" == "-h" ]]; then
    cat << EOF
🩺 Graphorama MCP Doctor

USAGE:
    $0

DESCRIPTION:
    Quick health check for Graphorama MCP installation.
    Tests binary installation, MCP functionality, and client integration.

CHECKS:
    🔍 Binary Installation
    🔌 MCP Protocol  
    🖥️  MCP Client Detection
    🌍 Environment

EXIT CODES:
    0 - All checks passed (warnings OK)
    1 - Critical issues found

This is a lightweight version that doesn't require external tools.
For comprehensive testing, use: ./scripts/verify-installation.sh

EOF
    exit 0
fi

# Run main function
main "$@"