#!/bin/bash
# Install Melexis Python packages to an active venv (if activated) or system Python

MELEXIS_SITE_PACKAGES="/mnt/c/Program Files/Melexis/Melexis IDE/plugins/com.melexis.mlxide.python_1.2.0.202408130945/python/Lib/site-packages"

# Determine destination: prefer active venv, fall back to system site-packages
if [ -n "$VIRTUAL_ENV" ]; then
    DEST_SITE_PACKAGES=$(python -c "import site; print(site.getsitepackages()[0])" 2>/dev/null)
    echo "Active venv detected: $VIRTUAL_ENV"
    echo "Installing into venv site-packages: $DEST_SITE_PACKAGES"
    SUDO=""
else
    DEST_SITE_PACKAGES=$(python3 -c "import site; print(site.getsitepackages()[0])" 2>/dev/null)
    echo "No venv active — installing into system Python..."
    echo "System site-packages: $DEST_SITE_PACKAGES"
    if [ ! -w "$DEST_SITE_PACKAGES" ]; then
        echo "Note: You may need sudo to install packages system-wide"
        SUDO="sudo"
    else
        SUDO=""
    fi
fi

if [ -z "$DEST_SITE_PACKAGES" ]; then
    echo "Error: Could not determine target site-packages directory"
    exit 1
fi

# Try to install from Melexis packages
if [ -d "$MELEXIS_SITE_PACKAGES" ]; then
    echo "Found Melexis packages at: $MELEXIS_SITE_PACKAGES"

    # Copy packages
    echo "Copying pylin..."
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylin" "$DEST_SITE_PACKAGES/"
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylin-"*".dist-info" "$DEST_SITE_PACKAGES/" 2>/dev/null || true

    echo "Copying pylinframe..."
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylinframe" "$DEST_SITE_PACKAGES/"
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pylinframe-"*".dist-info" "$DEST_SITE_PACKAGES/" 2>/dev/null || true

    echo "Copying pymumclient..."
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pymumclient" "$DEST_SITE_PACKAGES/"
    $SUDO cp -r "$MELEXIS_SITE_PACKAGES/pymumclient-"*".dist-info" "$DEST_SITE_PACKAGES/" 2>/dev/null || true

    # Copy all remaining dependencies
    echo "Copying all Melexis dependencies..."
    for pkg_dir in "$MELEXIS_SITE_PACKAGES"/*; do
        pkg=$(basename "$pkg_dir")

        # Skip dist-info directories and __pycache__
        if [[ "$pkg" == *".dist-info" ]] || [[ "$pkg" == "__pycache__" ]]; then
            continue
        fi

        # Only copy directories (packages)
        if [ -d "$pkg_dir" ]; then
            echo "  - $pkg"
            $SUDO cp -r "$pkg_dir" "$DEST_SITE_PACKAGES/"
            $SUDO cp -r "$MELEXIS_SITE_PACKAGES/${pkg}-"*".dist-info" "$DEST_SITE_PACKAGES/" 2>/dev/null || true
        fi
    done

    echo ""
    echo "Installation complete!"
    echo ""
    echo "Verifying installation..."
    python -c "import pylin; import pymumclient; print('✓ Packages imported successfully')" && echo "Success!" || echo "Failed - some packages missing"

else
    echo "Error: Melexis packages not found"
    exit 1
fi