#!/usr/bin/env bash
# create_configs.sh - Generate MCP client configuration files locally
#
# This script creates MCP client configuration files with absolute paths
# (since JSON files cannot use variable expansion like $HOME or ~).
#
# Usage:
#   ./create_configs.sh              # Interactive menu
#   ./create_configs.sh --all        # Generate all configs
#   ./create_configs.sh --client <name>  # Generate specific client config
#
# Supported clients:
#   - cursor: Cursor IDE
#   - kilocode: Kilocode IDE
#   - vscode: VS Code (user-level ~/.vscode/mcp.json)
#   - copilot: GitHub Copilot (VS Code 1.99+ workspace .vscode/mcp.json)
#   - copilot-cli: GitHub Copilot CLI (~/.copilot/mcp-config.json)
#   - opencode: OpenCode IDE
#   - claude: Claude Desktop

set -e

# ============================================================================
# Configuration
# ============================================================================

PROOT="$(cd "$(dirname "$0")" && pwd)"
START_SCRIPT_PATH="$PROOT/start-mcp.sh"
RUN_SCRIPT_PATH="$PROOT/run-mcp.sh"
SCRIPT_PATH=""
SCRIPT_NAME=""

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

# ============================================================================
# Helper Functions
# ============================================================================

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1" >&2
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1" >&2
}

# Check if script exists
check_script() {
    if [[ ! -f "$SCRIPT_PATH" ]]; then
        log_error "Launch script not found at: $SCRIPT_PATH"
        exit 1
    fi
    if [[ ! -x "$SCRIPT_PATH" ]]; then
        log_error "Launch script is not executable. Run: chmod +x $SCRIPT_PATH"
        exit 1
    fi
}

host_lisp_available() {
    command -v sbcl &>/dev/null ||
        command -v ecl &>/dev/null ||
        [[ -x /usr/local/bin/sbcl ]] ||
        [[ -x /usr/local/bin/ecl ]]
}

select_launch_script() {
    if host_lisp_available; then
        SCRIPT_PATH="$START_SCRIPT_PATH"
    elif command -v devenv &>/dev/null && [[ -x "$RUN_SCRIPT_PATH" ]]; then
        SCRIPT_PATH="$RUN_SCRIPT_PATH"
    else
        SCRIPT_PATH="$START_SCRIPT_PATH"
    fi

    SCRIPT_NAME="$(basename "$SCRIPT_PATH")"
}

# ============================================================================
# Config Generation Functions
# ============================================================================

generate_cursor_config() {
    local config_dir="$HOME/.cursor"
    local config_file="$config_dir/mcp.json"
    
    log_info "Generating Cursor MCP config..."
    
    mkdir -p "$config_dir"
    
    cat > "$config_file" << CURSORJSON
{
    "mcpServers": {
        "cl-tron-mcp": {
            "command": "$SCRIPT_PATH",
            "args": ["--stdio-only"],
            "disabled": false,
            "env": {}
        }
    }
}
CURSORJSON
    
    log_info "Created: $config_file"
    log_info "  - Command: $SCRIPT_PATH --stdio-only"
}

generate_kilocode_config() {
    local config_dir="$HOME/.kilocode"
    local config_file="$config_dir/mcp.json"
    
    log_info "Generating Kilocode MCP config..."
    
    mkdir -p "$config_dir"
    
    cat > "$config_file" << KILOJSON
{
    "mcpServers": {
        "cl-tron-mcp-stdio": {
            "command": "$SCRIPT_PATH",
            "args": ["--stdio-only"],
            "env": {},
            "alwaysAllow": [],
            "disabled": false
        },
        "cl-tron-mcp": {
            "command": "$SCRIPT_PATH",
            "args": ["--port", "4006"],
            "env": {},
            "alwaysAllow": [],
            "disabled": true
        }
    }
}
KILOJSON
    
    log_info "Created: $config_file"
    log_info "  - stdio: $SCRIPT_PATH --stdio-only"
    log_info "  - http: $SCRIPT_PATH --port 4006 (disabled by default)"
}

generate_vscode_config() {
    local config_dir="$HOME/.vscode"
    local config_file="$config_dir/mcp.json"
    
    log_info "Generating VS Code MCP config..."
    
    mkdir -p "$config_dir"
    
    cat > "$config_file" << VSCODEJSON
{
    "servers": {
        "cl-tron-mcp": {
            "type": "stdio",
            "command": "bash",
            "args": ["-c", "cd $PROOT && ./$SCRIPT_NAME --stdio-only"]
        }
    }
}
VSCODEJSON
    
    log_info "Created: $config_file"
    log_info "  - Command: cd $PROOT && ./$SCRIPT_NAME --stdio-only"
}

generate_copilot_config() {
    # GitHub Copilot uses VS Code's MCP infrastructure (VS Code 1.99+).
    # This generates the user-level settings snippet and the workspace .vscode/mcp.json.
    local workspace_dir=".vscode"
    local workspace_file="$workspace_dir/mcp.json"

    log_info "Generating GitHub Copilot (VS Code) MCP config..."

    # Workspace config
    mkdir -p "$workspace_dir"
    cat > "$workspace_file" << COPILOTWS
{
    "servers": {
        "cl-tron-mcp": {
            "type": "stdio",
            "command": "bash",
            "args": ["-c", "cd $PROOT && ./$SCRIPT_NAME --stdio-only"]
        }
    }
}
COPILOTWS

    log_info "Created workspace config: $workspace_file"
    log_info ""
    log_info "Alternatively, add to your VS Code user settings.json:"
    echo '{
    "mcp": {
        "servers": {
            "cl-tron-mcp": {
                "type": "stdio",
                "command": "bash",
                "args": ["-c", "cd '"$PROOT"' && ./'"$SCRIPT_NAME"' --stdio-only"]
            }
        }
    }
}'
    log_info ""
    log_info "Reload VS Code window (Ctrl+Shift+P → Reload Window) to activate."
}

generate_copilot_cli_config() {
    local config_dir="$HOME/.copilot"
    local config_file="$config_dir/mcp-config.json"

    log_info "Generating GitHub Copilot CLI MCP config..."

    mkdir -p "$config_dir"
    cat > "$config_file" << COPILOTCLIJSON
{
    "mcpServers": {
        "cl-tron-mcp": {
            "type": "local",
            "command": "bash",
            "args": ["-c", "cd $PROOT && ./$SCRIPT_NAME --stdio-only"],
            "env": {},
            "tools": ["*"]
        }
    }
}
COPILOTCLIJSON

    log_info "Created: $config_file"
    log_info "  - Command: cd $PROOT && ./$SCRIPT_NAME --stdio-only"
}

generate_devenv_config() {
    log_info "Generating devenv MCP client configs..."
    log_info ""
    log_info "devenv integration provides two usage modes:"
    log_info ""
    log_info "1. HTTP server (persistent, for development):"
    log_info "   Run: devenv up"
    log_info "   Tron starts on http://127.0.0.1:4006"
    log_info ""
    log_info "2. Stdio mode (for MCP clients like Cursor, Copilot CLI):"
    log_info "   Use 'tron-mcp' script (available inside devenv shell),"
    log_info "   or use 'devenv shell -- tron-mcp' from outside the shell."
    log_info ""
    log_info "Example MCP client config (Cursor .cursor/mcp.json):"
    cat << DEVENVCURSOR
{
    "mcpServers": {
        "cl-tron-mcp": {
            "command": "devenv",
            "args": ["shell", "--", "tron-mcp"],
            "cwd": "$PROOT"
        }
    }
}
DEVENVCURSOR
    log_info ""
    log_info "Example MCP client config (Copilot CLI ~/.copilot/mcp-config.json):"
    cat << DEVENVCOPILOT
{
    "mcpServers": {
        "cl-tron-mcp": {
            "type": "local",
            "command": "devenv",
            "args": ["shell", "--", "tron-mcp"],
            "env": { "DEVENV_ROOT": "$PROOT" },
            "tools": ["*"]
        }
    }
}
DEVENVCOPILOT
    log_info ""
    log_info "Tip: Run 'devenv shell' first so fasls are precompiled (tron-mcp:precompile task)."
    log_info "     Subsequent startups will be ~2s instead of ~8s."
}

generate_opencode_config() {
    local config_dir="$HOME/.config/opencode"
    local config_file="$config_dir/opencode.json"
    
    log_info "Generating OpenCode MCP config..."
    
    mkdir -p "$config_dir"
    
    # Check if config already exists
    if [[ -f "$config_file" ]]; then
        log_warn "OpenCode config already exists at: $config_file"
        log_warn "Please manually add the MCP configuration to your existing config."
        log_info ""
        log_info "Add this to your opencode.json:"
        echo '{'
        echo '    "$schema": "https://opencode.ai/config.json",'
        echo '    "mcp": {'
        echo '        "cl-tron-mcp": {'
        echo '            "type": "local",'
        echo "            \"command\": \"$SCRIPT_PATH\","
        echo '            "enabled": true'
        echo '        }'
        echo '    }'
        echo '}'
        return
    fi
    
    cat > "$config_file" << OPENCODEJSON
{
    "\$schema": "https://opencode.ai/config.json",
    "mcp": {
        "cl-tron-mcp": {
            "type": "local",
            "command": "$SCRIPT_PATH",
            "enabled": true
        }
    }
}
OPENCODEJSON
    
    log_info "Created: $config_file"
    log_info "  - Command: $SCRIPT_PATH"
}

generate_claude_config() {
    local config_dir="$HOME/.config"
    local config_file="$config_dir/claude_desktop_config.json"
    
    log_info "Generating Claude Desktop MCP config..."
    
    mkdir -p "$config_dir"
    
    # Check if config already exists
    if [[ -f "$config_file" ]]; then
        log_warn "Claude Desktop config already exists at: $config_file"
        log_warn "Please manually add the MCP configuration to your existing config."
        log_info ""
        log_info "Add this to your claude_desktop_config.json:"
        echo '{'
        echo '    "mcpServers": {'
        echo '        "cl-tron-mcp": {'
        echo "            \"command\": \"$SCRIPT_PATH\","
        echo '            "args": ["--stdio-only"]'
        echo '        }'
        echo '    }'
        echo '}'
        return
    fi
    
    cat > "$config_file" << CLAUDEJSON
{
    "mcpServers": {
        "cl-tron-mcp": {
            "command": "$SCRIPT_PATH",
            "args": ["--stdio-only"]
        }
    }
}
CLAUDEJSON
    
    log_info "Created: $config_file"
    log_info "  - Command: $SCRIPT_PATH --stdio-only"
}

# ============================================================================
# Menu Functions
# ============================================================================

show_menu() {
    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}  MCP Client Configuration Generator${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    echo "Select MCP client(s) to generate config for:"
    echo ""
    echo "  1) Cursor IDE"
    echo "  2) Kilocode IDE"
    echo "  3) VS Code"
    echo "  4) GitHub Copilot (VS Code)"
    echo "  5) GitHub Copilot CLI"
    echo "  6) OpenCode IDE"
    echo "  7) Claude Desktop"
    echo "  8) devenv integration (show instructions)"
    echo "  9) All of the above"
    echo " 10) Exit"
    echo ""
    echo -n "Enter choice (1-10): "
}

generate_all() {
    log_info "Generating all MCP client configurations..."
    echo ""
    
    generate_cursor_config
    echo ""
    
    generate_kilocode_config
    echo ""
    
    generate_vscode_config
    echo ""
    
    generate_copilot_config
    echo ""
    
    generate_copilot_cli_config
    echo ""
    
    generate_opencode_config
    echo ""
    
    generate_claude_config
    echo ""

    generate_devenv_config
    echo ""
    
    log_info "All configurations generated successfully!"
    log_info "Restart your MCP client(s) to pick up the new configuration."
}

# ============================================================================
# Main
# ============================================================================

main() {
    select_launch_script
    check_script
    
    # Parse command line arguments
    if [[ $# -gt 0 ]]; then
        case "$1" in
            --all)
                generate_all
                exit 0
                ;;
            --client)
                if [[ -z "$2" ]]; then
                    log_error "Usage: $0 --client <name>"
                    exit 1
                fi
                case "$2" in
                    cursor)
                        generate_cursor_config
                        ;;
                    kilocode)
                        generate_kilocode_config
                        ;;
                    vscode)
                        generate_vscode_config
                        ;;
                    copilot)
                        generate_copilot_config
                        ;;
                    copilot-cli)
                        generate_copilot_cli_config
                        ;;
                    opencode)
                        generate_opencode_config
                        ;;
                    claude)
                        generate_claude_config
                        ;;
                    devenv)
                        generate_devenv_config
                        ;;
                    *)
                        log_error "Unknown client: $2"
                        log_info "Supported clients: cursor, kilocode, vscode, copilot, copilot-cli, opencode, claude, devenv"
                        exit 1
                        ;;
                esac
                echo ""
                log_info "Configuration generated successfully!"
                log_info "Restart your MCP client to pick up the new configuration."
                exit 0
                ;;
            --help|-h)
                echo "Usage: $0 [OPTIONS]"
                echo ""
                echo "Options:"
                echo "  --all              Generate all MCP client configurations"
                echo "  --client <name>    Generate config for specific client"
                echo "                     (cursor, kilocode, vscode, copilot, copilot-cli, opencode, claude, devenv)"
                echo "  --help, -h         Show this help message"
                echo ""
                echo "Without arguments, shows an interactive menu."
                exit 0
                ;;
            *)
                log_error "Unknown option: $1"
                echo "Use --help for usage information."
                exit 1
                ;;
        esac
    fi
    
    # Interactive menu
    while true; do
        show_menu
        read -r choice
        
        case "$choice" in
            1)
                generate_cursor_config
                echo ""
                log_info "Restart Cursor to pick up the new configuration."
                ;;
            2)
                generate_kilocode_config
                echo ""
                log_info "Restart Kilocode to pick up the new configuration."
                ;;
            3)
                generate_vscode_config
                echo ""
                log_info "Restart VS Code to pick up the new configuration."
                ;;
            4)
                generate_copilot_config
                echo ""
                log_info "Reload VS Code window (Ctrl+Shift+P → Reload Window) to activate."
                ;;
            5)
                generate_copilot_cli_config
                echo ""
                log_info "Restart GitHub Copilot CLI to pick up the new configuration."
                ;;
            6)
                generate_opencode_config
                echo ""
                log_info "Restart OpenCode to pick up the new configuration."
                ;;
            7)
                generate_claude_config
                echo ""
                log_info "Restart Claude Desktop to pick up the new configuration."
                ;;
            8)
                generate_devenv_config
                ;;
            9)
                generate_all
                ;;
            10)
                log_info "Exiting."
                exit 0
                ;;
            *)
                log_error "Invalid choice. Please enter 1-10."
                ;;
        esac
        
        echo ""
        echo -n "Generate another config? (y/n): "
        read -r again
        if [[ "$again" != "y" && "$again" != "Y" ]]; then
            log_info "Exiting."
            exit 0
        fi
    done
}

main "$@"
