#!/bin/bash
# Installation script for pyPhotoAlbum
# Supports both system-wide and user-local installation

# Don't use set -e for dependency installation as some packages may already be installed
# We'll handle errors individually where needed

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

# Print functions
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
is_root() {
    [ "$(id -u)" -eq 0 ]
}

# Detect distribution
detect_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "$ID"
    else
        echo "unknown"
    fi
}

# Install system dependencies
install_dependencies() {
    local distro=$(detect_distro)

    print_info "Detected distribution: $distro"

    case "$distro" in
        fedora)
            print_info "Installing dependencies for Fedora..."
            # Use --skip-unavailable and --allowerasing to handle already installed packages
            sudo dnf install -y --skip-unavailable python3 python3-pip python3-pyqt6 python3-pyopengl \
                python3-numpy python3-pillow python3-reportlab python3-lxml || {
                print_warn "Some packages may already be installed or unavailable, continuing..."
            }
            ;;
        arch|cachyos)
            print_info "Installing dependencies for Arch/CachyOS..."
            sudo pacman -S --needed --noconfirm python python-pip python-pyqt6 \
                python-pyopengl python-numpy python-pillow python-reportlab python-lxml
            ;;
        ubuntu|debian)
            print_info "Installing dependencies for Ubuntu/Debian..."
            sudo apt update
            sudo apt install -y python3 python3-pip python3-pyqt6 python3-opengl \
                python3-numpy python3-pil python3-reportlab python3-lxml
            ;;
        *)
            print_warn "Unknown distribution. Please install dependencies manually."
            print_info "Required packages: python3, python3-pip, PyQt6, PyOpenGL, numpy, Pillow, reportlab, lxml"
            ;;
    esac
}

# Check if running in a virtual environment
in_virtualenv() {
    [ -n "$VIRTUAL_ENV" ] || [ -n "$CONDA_DEFAULT_ENV" ]
}

# Install Python package
install_package() {
    local install_mode=$1

    case "$install_mode" in
        system)
            print_info "Installing pyPhotoAlbum system-wide..."
            sudo pip install --upgrade .
            ;;
        venv)
            print_info "Installing pyPhotoAlbum in virtual environment..."
            pip install --upgrade .
            ;;
        user-force)
            print_info "Installing pyPhotoAlbum for current user (forcing --user)..."
            pip install --user --upgrade .
            ;;
        *)
            print_info "Installing pyPhotoAlbum for current user..."
            pip install --user --upgrade .
            ;;
    esac
}

# Install desktop integration
install_desktop_integration() {
    local install_mode=$1

    if [ "$install_mode" = "system" ]; then
        print_info "Installing desktop integration system-wide..."

        # Install desktop file
        sudo install -Dm644 pyphotoalbum.desktop \
            /usr/share/applications/pyphotoalbum.desktop

        # Install icons in multiple sizes for GNOME
        print_info "Installing application icons..."

        # Install main icon (256x256)
        sudo install -Dm644 pyPhotoAlbum/icons/icon.png \
            /usr/share/icons/hicolor/256x256/apps/pyphotoalbum.png

        # Install additional sizes if they exist
        for size in 16 22 24 32 48 64 128 512; do
            icon_file="pyPhotoAlbum/icons/icon-${size}x${size}.png"
            if [ -f "$icon_file" ]; then
                sudo install -Dm644 "$icon_file" \
                    "/usr/share/icons/hicolor/${size}x${size}/apps/pyphotoalbum.png"
            fi
        done

        # Update desktop database
        if command -v update-desktop-database &> /dev/null; then
            sudo update-desktop-database /usr/share/applications
        fi

        # Update icon cache
        if command -v gtk-update-icon-cache &> /dev/null; then
            print_info "Updating icon cache..."
            sudo gtk-update-icon-cache -f /usr/share/icons/hicolor/
        fi
    else
        print_info "Installing desktop integration for current user..."

        # Create directories if they don't exist
        mkdir -p ~/.local/share/applications

        # Copy desktop file and update Exec paths to use full path
        cp pyphotoalbum.desktop ~/.local/share/applications/
        sed -i "s|Exec=pyphotoalbum|Exec=$HOME/.local/bin/pyphotoalbum|g" ~/.local/share/applications/pyphotoalbum.desktop

        # Install icons in multiple sizes for GNOME
        print_info "Installing application icons..."

        # Install main icon (256x256)
        mkdir -p ~/.local/share/icons/hicolor/256x256/apps
        cp pyPhotoAlbum/icons/icon.png ~/.local/share/icons/hicolor/256x256/apps/pyphotoalbum.png

        # Generate and install additional sizes for better display
        if command -v magick &> /dev/null || command -v convert &> /dev/null; then
            for size in 48 64 128; do
                mkdir -p ~/.local/share/icons/hicolor/${size}x${size}/apps
                if command -v magick &> /dev/null; then
                    magick pyPhotoAlbum/icons/icon.png -resize ${size}x${size} ~/.local/share/icons/hicolor/${size}x${size}/apps/pyphotoalbum.png 2>/dev/null
                else
                    convert pyPhotoAlbum/icons/icon.png -resize ${size}x${size} ~/.local/share/icons/hicolor/${size}x${size}/apps/pyphotoalbum.png 2>/dev/null
                fi
            done
        fi

        # Install additional sizes if they exist
        for size in 16 22 24 32 48 64 128 512; do
            icon_file="pyPhotoAlbum/icons/icon-${size}x${size}.png"
            if [ -f "$icon_file" ]; then
                mkdir -p ~/.local/share/icons/hicolor/${size}x${size}/apps
                cp "$icon_file" ~/.local/share/icons/hicolor/${size}x${size}/apps/pyphotoalbum.png
            fi
        done

        # Update desktop database
        if command -v update-desktop-database &> /dev/null; then
            update-desktop-database ~/.local/share/applications
        fi

        # Update icon cache
        if command -v gtk-update-icon-cache &> /dev/null; then
            print_info "Updating icon cache..."
            gtk-update-icon-cache -f ~/.local/share/icons/hicolor/
        fi
    fi
}

# Main installation
main() {
    echo "========================================"
    echo "   pyPhotoAlbum Installation Script    "
    echo "========================================"
    echo ""

    # Check for required files
    if [ ! -f "pyproject.toml" ]; then
        print_error "pyproject.toml not found. Please run this script from the project root."
        exit 1
    fi

    # Determine installation mode
    local install_mode="user"
    if is_root || [ "${1}" = "--system" ]; then
        install_mode="system"
    fi

    # Check if in virtualenv and warn user
    if in_virtualenv; then
        print_warn "Running in a virtual environment"
        echo "Where do you want to install?"
        echo "1) Virtual environment (default)"
        echo "2) User installation (~/.local)"
        echo "3) System-wide (requires sudo)"
        echo ""
        read -p "Enter your choice [1-3]: " venv_choice

        case "$venv_choice" in
            2)
                install_mode="user-force"
                ;;
            3)
                install_mode="system"
                ;;
            *)
                install_mode="venv"
                ;;
        esac
        echo ""
    fi

    print_info "Installation mode: $install_mode"
    echo ""

    # Ask user what to install
    echo "What would you like to install?"
    echo "1) Dependencies only"
    echo "2) Application only (no dependencies)"
    echo "3) Everything (recommended)"
    echo "4) Exit"
    echo ""
    read -p "Enter your choice [1-4]: " choice

    case "$choice" in
        1)
            install_dependencies
            ;;
        2)
            install_package "$install_mode"
            install_desktop_integration "$install_mode"
            ;;
        3)
            install_dependencies
            install_package "$install_mode"
            install_desktop_integration "$install_mode"
            ;;
        4)
            print_info "Installation cancelled."
            exit 0
            ;;
        *)
            print_error "Invalid choice. Exiting."
            exit 1
            ;;
    esac

    echo ""
    print_info "Installation complete!"
    echo ""
    echo "You can now run pyPhotoAlbum by:"
    echo "  1) Running 'pyphotoalbum' in the terminal"
    echo "  2) Finding 'pyPhotoAlbum' in your application menu"
    echo ""

    if [ "$install_mode" = "user" ]; then
        print_warn "Note: If the 'pyphotoalbum' command is not found, make sure ~/.local/bin is in your PATH"
        echo "Add this to your ~/.bashrc or ~/.zshrc:"
        echo "  export PATH=\"\$HOME/.local/bin:\$PATH\""
    fi
}

# Run main function
main "$@"
