#!/bin/bash

set -e

MANIFEST_URL="https://taosinstallers.blob.core.windows.net/tdengine-excel-add-in/manifest.xml"
ADDIN_NAME="VueOfficeAddin"
IDMP_URL="https://localhost:6034"
INSTALL_DIR="$HOME/Library/Containers/com.microsoft.Excel/Data/Documents/wef/"

enable_runtime_logging_macos() {
    echo "🔧 Enabling Excel Add-in runtime logging..."
    if [[ "$EUID" -eq 0 ]]; then
        echo "❌ Please do NOT run this script as root or using sudo"
        return 1
    fi
    
    local force_close="${1:-false}"
    if ! check_excel_process_macos "$force_close"; then
        echo "⚠️ Excel process check failed, continuing with enabling runtime logging..."
    fi
    if defaults write com.microsoft.Excel CEFRuntimeLoggingFile -string "tdengine_eai.log" 2>/dev/null; then
        echo "✅ Excel runtime logging enabled"
        echo " Restart Excel to apply changes"
        echo "📂 Log file will be created at:"
        echo "   ~/Library/Containers/com.microsoft.Excel/Data/tdengine_eai.log"
        echo ""
        return 0
    else
        echo "⚠️ Failed to enable runtime logging"
        return 1
    fi
}

disable_runtime_logging_macos() {
    echo "🔧 Disabling Excel Add-in runtime logging..."

    local force_close="${1:-false}"
    if ! check_excel_process_macos "$force_close"; then
        echo "⚠️ Excel process check failed, continuing with disabling runtime logging..."
    fi

    defaults delete com.microsoft.Excel CEFRuntimeLoggingFile 2>/dev/null || true
    echo "✅ Runtime logging disabled"
}

check_excel_process_macos() {
    local force_close="${1:-false}"
    
    if pgrep "Microsoft Excel" > /dev/null 2>&1; then
        echo "⚠️ Microsoft Excel is currently running on macOS"
        echo "📋 Excel must be closed to access the container directory"
        echo ""
        
        if [[ "$force_close" == "true" ]]; then
            echo "🔄 Force closing Microsoft Excel..."
            pkill "Microsoft Excel" 2>/dev/null || true
            sleep 3
            
            if pgrep "Microsoft Excel" > /dev/null 2>&1; then
                echo "❌ Failed to close Excel automatically"
                echo "Please manually close Excel and run this script again"
                return 1
            else
                echo "✅ Excel closed successfully"
            fi
        else
            # Only ask for interactive input if stdin is a terminal
            if [[ -t 0 ]]; then
                read -p "Do you want to close Excel automatically? [y/N]: " close_excel
                
                if [[ "$close_excel" =~ ^[Yy]$ ]]; then
                    echo "🔄 Closing Microsoft Excel..."
                    pkill "Microsoft Excel" 2>/dev/null || true
                    sleep 3
                    
                    if pgrep "Microsoft Excel" > /dev/null 2>&1; then
                        echo "❌ Failed to close Excel automatically"
                        echo "Please manually close Excel and run this script again"
                        return 1
                    else
                        echo "✅ Excel closed successfully"
                    fi
                else
                    echo "❌ Please close Excel manually and run this script again"
                    echo "💡 You can close Excel by: Cmd+Q or Excel → Quit Excel"
                    return 1
                fi
            else
                echo "❌ Excel is running but cannot prompt for input (non-interactive mode)"
                echo "💡 Options:"
                echo "   1. Close Excel manually first, then run: curl install.sh | sh -s uninstall"
                echo "   2. Use force close: curl install.sh | sh -s uninstall --force-close"
                echo "   3. Run locally: ./install.sh uninstall"
                return 1
            fi
        fi
    else
        echo "✅ Excel is not running - container directory accessible"
    fi
    return 0
}

prepare_manifest_macos() {
    if ! check_excel_process_macos "$FORCE_CLOSE"; then
        return 1
    fi
    
    if ! mkdir -p "$INSTALL_DIR" 2>/dev/null; then
        echo "❌ Failed to create directory: $INSTALL_DIR"
        echo "💡 This usually means Excel is still running or permissions issue"
        echo "Try: killall 'Microsoft Excel' && sleep 3"
        return 1
    fi
    
    if [[ -n "$CUSTOM_MANIFEST_DIR" ]]; then
        local src_manifest="$CUSTOM_MANIFEST_DIR/manifest.xml"
        if [[ ! -f "$src_manifest" ]]; then
            echo "❌ manifest.xml not found in: $CUSTOM_MANIFEST_DIR"
            return 1
        fi
        if cp "$src_manifest" "$INSTALL_DIR/manifest.xml"; then
            echo "✅ manifest.xml copied from $CUSTOM_MANIFEST_DIR"
        else
            echo "❌ Failed to copy manifest.xml from $CUSTOM_MANIFEST_DIR"
            return 1
        fi
    else
        if curl -fsSL "$MANIFEST_URL" -o "$INSTALL_DIR/manifest.xml" 2>/dev/null; then
            echo "✅ manifest.xml downloaded to $INSTALL_DIR"
        else
            echo "❌ Failed to download manifest.xml"
            return 1
        fi
    fi

    return 0
}

uninstall_macos() {
    local force_close="${1:-false}"
    echo "📋 Starting macOS uninstallation..."
    
    if ! check_excel_process_macos "$force_close"; then
        echo "⚠️ Excel process check failed, continuing with uninstallation..."
    fi
    
    disable_runtime_logging_macos

    if [[ -d "$INSTALL_DIR" ]]; then
        if rm -rf "$INSTALL_DIR" 2>/dev/null; then
            echo "✅ Installation directory removed: $INSTALL_DIR"
        else
            echo "❌ Failed to remove directory (Excel might still be running)"
            return 1
        fi
    else
        echo "⚠️ Installation directory not found: $INSTALL_DIR"
    fi
    
    echo "✅ macOS uninstallation completed!"
    return 0
}

# Main program
if [[ "$OSTYPE" != "darwin"* ]]; then
    echo "❌ This script is for macOS only"
    echo "For Windows, please use: install.ps1"
    exit 1
fi

# Support command line arguments for non-interactive mode
CHOICE=""
FORCE_CLOSE="false"
CUSTOM_URL=""
CUSTOM_MANIFEST_DIR=""

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        install|1)
            CHOICE="1"
            shift
            ;;
        uninstall|2)
            CHOICE="2"
            shift
            ;;
        enable-logging-only)
            CHOICE="3"
            shift
            ;;
        disable-logging-only)
            CHOICE="4"
            shift
            ;;
        --force-close)
            FORCE_CLOSE="true"
            shift
            ;;
        --url)
            CUSTOM_URL="$2"
            shift 2
            ;;
        --manifest-dir)
            CUSTOM_MANIFEST_DIR="$2"
            shift 2
            ;;
        --enable-logging)
            ENABLE_LOGGING="true"
            shift
            ;;
        *)
            echo "❌ Invalid argument: $1"
            echo "Usage: $0 [install|uninstall|enable-logging-only|disable-logging-only] [--force-close] [--url URL] [--manifest-dir DIR] [--enable-logging]"
            exit 1
            ;;
    esac
done

if [[ -z "$CHOICE" ]]; then
    echo ""
    echo "=== Excel DataIn Installation Tool (macOS) ==="
    echo "1. Install (download manifest + configure)"
    echo "2. Uninstall (delete files)"
    echo "3. Enable runtime logging only"
    echo "4. Disable runtime logging only"
    read -p "Enter 1, 2, 3, or 4: " CHOICE
fi

echo ""

if [[ "$CHOICE" == "1" ]]; then
    echo "📋 Starting macOS installation..."
    
    if ! prepare_manifest_macos "$FORCE_CLOSE"; then
        echo ""
        echo "❌ Installation failed"
        echo "💡 Common solutions:"
        echo "   • Close Microsoft Excel completely (Cmd+Q)"
        echo "   • Wait 5-10 seconds after closing Excel"
        echo "   • Use --manifest-dir to install a local manifest.xml"
        echo "   • Try running the script again"
        exit 1
    fi
    
    # Use command line URL if provided, otherwise prompt for input (if interactive)
    if [[ -n "$CUSTOM_URL" ]]; then
        IDMP_URL="$CUSTOM_URL"
        echo "✅ Using provided IDMP URL: $IDMP_URL"
    elif [[ -t 0 ]]; then
        # Interactive mode
        read -p "Enter IDMP server URL (default: $IDMP_URL): " INPUT_URL
        if [[ -n "$INPUT_URL" ]]; then
            IDMP_URL="$INPUT_URL"
        fi
    else
        # Non-interactive mode without URL parameter
        echo "✅ Using default IDMP URL: $IDMP_URL"
        echo "💡 To use custom URL in non-interactive mode: --url https://your-server:port"
    fi
    
    # Update URL in manifest.xml
    if sed -i.bak "s#https://localhost:6034#${IDMP_URL}#g" "$INSTALL_DIR/manifest.xml" 2>/dev/null; then
        rm -f "$INSTALL_DIR/manifest.xml.bak"
        echo "✅ manifest.xml URL updated to: $IDMP_URL"
    else
        echo "❌ Failed to update URL in manifest.xml"
    fi

    if [[ "$ENABLE_LOGGING" == "true" ]]; then
        if enable_runtime_logging_macos "$FORCE_CLOSE"; then
            echo "✅ Runtime logging enabled as per request"
        else
            echo "⚠️ Runtime logging setup failed"
        fi
    fi
    
    echo ""
    echo "✅ macOS installation completed!"
    echo ""
    echo "📝 How to activate the add-in in Excel:"
    echo "1. Open Microsoft Excel"
    echo "2. Go to Excel Start Page (or click 'File' → 'New')"
    echo "3. Look for 'Add-ins' section on the start page"
    echo "4. Click on 'TDengine Data Connection' icon"
    echo "5. ✅ The 'TDengine Data Connection' tab will appear in the ribbon!"
    echo ""
elif [[ "$CHOICE" == "2" ]]; then
    if ! uninstall_macos "$FORCE_CLOSE"; then
        echo ""
        echo "❌ Uninstallation encountered errors"
        exit 1
    fi
elif [[ "$CHOICE" == "3" ]]; then
    if enable_runtime_logging_macos "$FORCE_CLOSE"; then
        echo "✅ Runtime logging enabled for debugging"
    else
        echo "⚠️ Runtime logging setup failed"
        exit 1
    fi
    exit 0
elif [[ "$CHOICE" == "4" ]]; then
    disable_runtime_logging_macos "$FORCE_CLOSE"
    echo "✅ Runtime logging disabled as per request"
    exit 0
else
    echo "❌ Invalid choice. Please run the script again and select a valid option."
    exit 1
fi

echo ""
echo "📋 Process completed"