#!/usr/bin/env bash
# Playwright Docker Wrapper for Fedora
#
# Playwright does not officially support Fedora as a host OS. This wrapper
# executes Playwright commands inside the official Microsoft Playwright Docker
# container, bypassing local dependency issues while maintaining functionality.
#
# Usage:
#   ./scripts/playwright [playwright-args...]
#   ./scripts/playwright install
#   ./scripts/playwright install --with-deps chromium firefox webkit
#
# Environment Variables:
#   PLAYWRIGHT_IMAGE    Docker image to use (default: mcr.microsoft.com/playwright:v1.49.1-noble)
#   PLAYWRIGHT_NO_PULL  Skip pulling image if set to 'true'

set -euo pipefail

# Configuration
# Use custom GHCR image by default (has Playwright pre-installed)
# Can override with PLAYWRIGHT_IMAGE environment variable for testing
PLAYWRIGHT_IMAGE="${PLAYWRIGHT_IMAGE:-ghcr.io/bdperkin/nhl-scrabble-playwright:latest}"
PLAYWRIGHT_NO_PULL="${PLAYWRIGHT_NO_PULL:-false}"

# Detect repository root (script is in scripts/ subdirectory)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# 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 colored message
log() {
    local color="$1"
    shift
    echo -e "${color}[playwright-docker]${NC} $*"
}

# Check if Docker is available
if ! command -v docker &> /dev/null; then
    log "${RED}" "ERROR: Docker is not installed or not in PATH"
    log "${YELLOW}" "Install Docker: https://docs.docker.com/get-docker/"
    exit 1
fi

# Check if Docker daemon is running
if ! docker info &> /dev/null; then
    log "${RED}" "ERROR: Docker daemon is not running"
    log "${YELLOW}" "Start Docker: sudo systemctl start docker"
    exit 1
fi

# Pull Playwright image if needed
if [[ "${PLAYWRIGHT_NO_PULL}" != "true" ]]; then
    if ! docker images "${PLAYWRIGHT_IMAGE}" --format '{{.Repository}}:{{.Tag}}' | grep -q "${PLAYWRIGHT_IMAGE}"; then
        log "${BLUE}" "Pulling Playwright Docker image: ${PLAYWRIGHT_IMAGE}"
        if ! docker pull "${PLAYWRIGHT_IMAGE}"; then
            log "${RED}" "ERROR: Failed to pull Docker image"
            exit 1
        fi
    fi
fi

# Determine working directory relative to repo root
# If called from qa/web, maintain that context
CURRENT_DIR="$(pwd)"
if [[ "${CURRENT_DIR}" == "${REPO_ROOT}"* ]]; then
    # Inside repo, calculate relative path
    REL_PATH="${CURRENT_DIR#${REPO_ROOT}}"
    REL_PATH="${REL_PATH#/}" # Remove leading slash
    WORKDIR="/work/${REL_PATH}"
else
    # Outside repo, use /work as working directory
    WORKDIR="/work"
fi

# Run as current user to avoid permission issues
# Custom image has pwuser created, but we override to match host UID/GID
# This ensures generated files are owned by the current user

# Build Docker run command
# Use :z flag for SELinux systems to allow container write access
# Run as root to avoid Firefox permission issues in Docker
DOCKER_CMD=(
    docker run
    --rm                                    # Remove container after exit
    --interactive                           # Keep STDIN open
    --network host                          # Access host network (for localhost:5000)
    --volume "${REPO_ROOT}:/work:z"        # Mount repository (with SELinux label)
    --shm-size=2gb                          # Increase shared memory for Firefox
    --workdir "${WORKDIR}"                 # Set working directory
    --env "HOME=/home/pwuser"              # Set HOME for Playwright
    --env "PLAYWRIGHT_BROWSERS_PATH=/home/pwuser/.cache/ms-playwright"  # Browser cache (in image)
)

# Add TTY flag only if running in a terminal
if [[ -t 1 ]]; then
    DOCKER_CMD+=(--tty)
fi

# Add environment variables for Playwright from host
# This allows overriding Playwright settings via environment
declare -a PLAYWRIGHT_ENVS=(
    "PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD"
    "PLAYWRIGHT_BROWSERS_PATH"
    "DEBUG"
    "PWDEBUG"
)

for env_var in "${PLAYWRIGHT_ENVS[@]}"; do
    if [[ -n "${!env_var:-}" ]]; then
        DOCKER_CMD+=(--env "${env_var}=${!env_var}")
    fi
done

# Special handling for 'install' command to ensure browsers are cached
if [[ "${1:-}" == "install" ]]; then
    log "${BLUE}" "Installing Playwright browsers in Docker container"
    log "${YELLOW}" "Browsers will be cached in: ${HOME}/.cache/ms-playwright"
fi

# Execute Playwright command in container
log "${GREEN}" "Running: playwright $*"
log "${BLUE}" "Image: ${PLAYWRIGHT_IMAGE}"
log "${BLUE}" "Working directory: ${WORKDIR}"

if [[ "${1:-}" == "install" ]]; then
    log "${BLUE}" "Installing browsers (Playwright already in image)..."
fi

# Run playwright command (Playwright already installed in custom image)
"${DOCKER_CMD[@]}" \
    "${PLAYWRIGHT_IMAGE}" \
    playwright "$@"

EXIT_CODE=$?

if [[ ${EXIT_CODE} -eq 0 ]]; then
    log "${GREEN}" "Command completed successfully"
else
    log "${RED}" "Command failed with exit code ${EXIT_CODE}"
fi

exit ${EXIT_CODE}
