#!/bin/bash
set -e

echo "===> Starting MSD Broken Link Checker setup..."

# Check Python version
python_version=$(python --version | cut -d' ' -f2)
echo "===> Using Python version: $python_version"

# Check if running Python 3.13
if [[ $python_version == 3.13* ]]; then
    echo "===> Python 3.13 detected - ensuring compatibility..."
    # Python 3.13 has removed several deprecated modules listed in PEP 594
    # No specific action needed for this app, but noted for awareness
fi

# Check if we're running in a Docker/Dokku environment
IN_DOCKER=false
if [ -f "/.dockerenv" ] || grep -q "docker\|lxc" /proc/1/cgroup 2>/dev/null; then
    IN_DOCKER=true
    echo "===> Detected Docker/Dokku environment"
fi

# Check available disk space
if [ "$IN_DOCKER" = true ]; then
    available_space=$(df -k / | tail -1 | awk '{print $4}')
    echo "===> Available space in root filesystem: ${available_space}KB"
    
    if [ "$available_space" -lt 150000 ]; then  # 150MB
        echo "===> WARNING: Low disk space detected. Some operations may be skipped."
        LOW_DISK_SPACE=true
    fi
fi

# Verify Playwright is installed and functional
echo "===> Verifying Playwright installation..."
if python -c "import playwright; print('Playwright version:', playwright.__version__)" 2>/dev/null; then
    echo "===> Playwright is installed"
    
    # Check if browser is already set up
    if [ -d "/ms-playwright/chromium-1091" ] || [ -d "/root/.cache/ms-playwright" ]; then
        echo "===> Chromium browser already installed"
    else
        echo "===> Chromium browser not found in expected location"
        if [ "$IN_DOCKER" = false ] && [ "$LOW_DISK_SPACE" != true ]; then
            echo "===> Installing Playwright browsers (lightweight)..."
            python -m playwright install chromium
        else
            echo "===> Skipping browser installation in Docker environment or due to low disk space"
        fi
    fi
else
    echo "===> WARNING: Playwright not found, some features may not work"
    
    if [ "$IN_DOCKER" = false ] && [ "$LOW_DISK_SPACE" != true ]; then
        echo "===> Installing Python dependencies..."
        pip install --no-cache-dir playwright
        python -m playwright install chromium
    else
        echo "===> Skipping installation due to Docker environment or low disk space"
    fi
fi

# Check if deps are needed, but only install minimal ones if in Docker
if [ "$IN_DOCKER" = true ] && [ "$LOW_DISK_SPACE" != true ]; then
    echo "===> Checking for minimal system dependencies..."
    # Check for Xvfb as a proxy for browser dependencies
    if ! command -v Xvfb &> /dev/null; then
        echo "===> Some browser dependencies might be missing but will be skipped in Docker"
    fi
fi

# Copy Excel files to app directory if needed
echo "===> Ensuring Excel files are in the app directory..."
if [ ! -f "app/URLs.xlsx" ]; then
    if [ -f "URLs.xlsx" ]; then
        cp URLs.xlsx app/
        echo "Copied URLs.xlsx to app directory"
    else
        echo "WARNING: URLs.xlsx not found"
    fi
fi

if [ ! -f "app/URLs_without_login.xlsx" ]; then
    if [ -f "URLs_without_login.xlsx" ]; then
        cp URLs_without_login.xlsx app/
        echo "Copied URLs_without_login.xlsx to app directory"
    else
        echo "WARNING: URLs_without_login.xlsx not found"
    fi
fi

# Verify environment variables
echo "===> Checking environment variables..."
if [ ! -f ".env" ]; then
    echo "WARNING: .env file not found. Make sure to set up the following environment variables:"
    echo "  - MSD_USERNAME"
    echo "  - MSD_PASSWORD"
    echo "  - SMTP_SERVER"
    echo "  - SMTP_PORT"
    echo "  - EMAIL_SENDER"
    echo "  - EMAIL_USERNAME"
    echo "  - EMAIL_PASSWORD"
    echo "  - EMAIL_RECIPIENTS"
else
    echo ".env file found. Using environment variables from .env file."
fi

# Create a log directory
echo "===> Creating log directory..."
mkdir -p logs
mkdir -p app/logs

echo "===> Setup completed successfully!"

# Note about server-side cron
echo "===> NOTE: This application uses server-side cron via Dokku."
echo "===> Please refer to README.md for instructions on setting up scheduled tasks." 