#!/bin/bash
# Debian/Ubuntu installation script for pyPhotoAlbum
# Creates a virtual environment and installs all dependencies

set -e

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

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

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

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

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$SCRIPT_DIR/venv"
INSTALL_DIR="$HOME/.local"
BIN_DIR="$INSTALL_DIR/bin"

echo "========================================"
echo "  pyPhotoAlbum Debian Installation     "
echo "========================================"
echo ""

# Check if running on Debian/Ubuntu
if [ -f /etc/os-release ]; then
    . /etc/os-release
    if [[ "$ID" != "debian" && "$ID" != "ubuntu" && "$ID_LIKE" != *"debian"* && "$ID_LIKE" != *"ubuntu"* ]]; then
        print_warn "This script is designed for Debian/Ubuntu-based systems."
        print_warn "Detected: $PRETTY_NAME"
        read -p "Continue anyway? [y/N]: " continue_choice
        if [[ ! "$continue_choice" =~ ^[Yy]$ ]]; then
            exit 1
        fi
    else
        print_info "Detected: $PRETTY_NAME"
    fi
fi

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

# Step 1: Install system dependencies
print_step "Installing system dependencies..."
echo ""

# Check if we need sudo
if [ "$(id -u)" -ne 0 ]; then
    SUDO="sudo"
else
    SUDO=""
fi

$SUDO apt update

# Install Python and venv support
print_info "Installing Python and venv support..."
$SUDO apt install -y python3 python3-venv python3-pip

# Install system libraries required for PyQt6 and OpenGL
print_info "Installing Qt6 and OpenGL libraries..."
$SUDO apt install -y \
    libgl1-mesa-dev \
    libglu1-mesa-dev \
    libxcb-xinerama0 \
    libxcb-cursor0 \
    libxkbcommon0 \
    libdbus-1-3 \
    libegl1 \
    libfontconfig1 \
    libfreetype6 \
    libx11-6 \
    libx11-xcb1 \
    libxcb1 \
    libxcb-glx0 \
    libxcb-icccm4 \
    libxcb-image0 \
    libxcb-keysyms1 \
    libxcb-randr0 \
    libxcb-render0 \
    libxcb-render-util0 \
    libxcb-shape0 \
    libxcb-shm0 \
    libxcb-sync1 \
    libxcb-xfixes0 \
    libxcb-xkb1 \
    libxkbcommon-x11-0 \
    libglib2.0-0 \
    libgtk-3-0 || print_warn "Some packages may not be available, continuing..."

echo ""

# Step 2: Create virtual environment
print_step "Creating virtual environment..."
echo ""

if [ -d "$VENV_DIR" ]; then
    print_warn "Virtual environment already exists at $VENV_DIR"
    read -p "Remove and recreate? [y/N]: " recreate_choice
    if [[ "$recreate_choice" =~ ^[Yy]$ ]]; then
        print_info "Removing existing virtual environment..."
        rm -rf "$VENV_DIR"
    else
        print_info "Using existing virtual environment..."
    fi
fi

if [ ! -d "$VENV_DIR" ]; then
    print_info "Creating virtual environment at $VENV_DIR..."
    python3 -m venv "$VENV_DIR"
fi

# Activate virtual environment
source "$VENV_DIR/bin/activate"

# Upgrade pip
print_info "Upgrading pip..."
pip install --upgrade pip

echo ""

# Step 3: Install Python dependencies
print_step "Installing Python dependencies..."
echo ""

print_info "Installing pyPhotoAlbum and its dependencies..."
pip install -e "$SCRIPT_DIR"

echo ""

# Step 4: Create launcher script
print_step "Creating launcher script..."
echo ""

mkdir -p "$BIN_DIR"

cat > "$BIN_DIR/pyphotoalbum" << EOF
#!/bin/bash
# pyPhotoAlbum launcher script
# Activates the virtual environment and runs the application

SCRIPT_DIR="$SCRIPT_DIR"
VENV_DIR="$VENV_DIR"

# Activate venv and run
source "\$VENV_DIR/bin/activate"
exec python "\$SCRIPT_DIR/pyPhotoAlbum/main.py" "\$@"
EOF

chmod +x "$BIN_DIR/pyphotoalbum"
print_info "Launcher script created at $BIN_DIR/pyphotoalbum"

echo ""

# Step 5: Install desktop integration
print_step "Installing desktop integration..."
echo ""

DESKTOP_DIR="$HOME/.local/share/applications"
ICON_DIR="$HOME/.local/share/icons/hicolor"

mkdir -p "$DESKTOP_DIR"
mkdir -p "$ICON_DIR/256x256/apps"

# Create desktop file with correct path
cat > "$DESKTOP_DIR/pyphotoalbum.desktop" << EOF
[Desktop Entry]
Type=Application
Name=pyPhotoAlbum
GenericName=Photo Album Designer
Comment=Design photo albums and export them to PDF
Exec=$BIN_DIR/pyphotoalbum %F
Icon=pyphotoalbum
Terminal=false
Categories=Graphics;Photography;Qt;
Keywords=photo;album;pdf;design;layout;
MimeType=application/x-pyphotoalbum-project;
StartupNotify=true
StartupWMClass=pyPhotoAlbum
Actions=NewProject;

[Desktop Action NewProject]
Name=New Project
Exec=$BIN_DIR/pyphotoalbum --new
EOF

print_info "Desktop file created at $DESKTOP_DIR/pyphotoalbum.desktop"

# Copy icon
if [ -f "$SCRIPT_DIR/pyPhotoAlbum/icons/icon.png" ]; then
    cp "$SCRIPT_DIR/pyPhotoAlbum/icons/icon.png" "$ICON_DIR/256x256/apps/pyphotoalbum.png"
    print_info "Icon installed"

    # Generate additional icon sizes if ImageMagick is available
    if command -v convert &> /dev/null || command -v magick &> /dev/null; then
        for size in 48 64 128; do
            mkdir -p "$ICON_DIR/${size}x${size}/apps"
            if command -v magick &> /dev/null; then
                magick "$SCRIPT_DIR/pyPhotoAlbum/icons/icon.png" -resize ${size}x${size} "$ICON_DIR/${size}x${size}/apps/pyphotoalbum.png" 2>/dev/null
            else
                convert "$SCRIPT_DIR/pyPhotoAlbum/icons/icon.png" -resize ${size}x${size} "$ICON_DIR/${size}x${size}/apps/pyphotoalbum.png" 2>/dev/null
            fi
        done
        print_info "Additional icon sizes generated"
    fi
fi

# Update desktop database
if command -v update-desktop-database &> /dev/null; then
    update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true
fi

# Update icon cache
if command -v gtk-update-icon-cache &> /dev/null; then
    gtk-update-icon-cache -f "$ICON_DIR" 2>/dev/null || true
fi

echo ""

# Deactivate venv
deactivate

# Final message
echo "========================================"
echo -e "${GREEN}  Installation complete!${NC}"
echo "========================================"
echo ""
echo "You can now run pyPhotoAlbum by:"
echo "  1) Running 'pyphotoalbum' in the terminal"
echo "  2) Finding 'pyPhotoAlbum' in your application menu"
echo ""

# Check if ~/.local/bin is in PATH
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
    print_warn "~/.local/bin is not in your PATH"
    echo ""
    echo "Add this to your ~/.bashrc or ~/.profile:"
    echo "  export PATH=\"\$HOME/.local/bin:\$PATH\""
    echo ""
    echo "Then run: source ~/.bashrc"
fi

echo ""
echo "To run directly from source directory:"
echo "  $SCRIPT_DIR/launch-pyphotoalbum.sh"
echo ""
