#!/usr/bin/env bash
# Build and optionally push the custom Playwright Docker image
#
# This script builds the custom Playwright Docker image for local testing
# or pushes it to GitHub Container Registry (GHCR).
#
# Usage:
#   ./scripts/build-playwright-image           # Build locally only
#   ./scripts/build-playwright-image --push    # Build and push to GHCR
#   ./scripts/build-playwright-image --test    # Build and test locally
#
# Environment Variables:
#   GITHUB_TOKEN    GitHub Personal Access Token for GHCR push (required for --push)
#   IMAGE_TAG       Custom tag (default: latest)

set -euo pipefail

# Configuration
REPO_OWNER="bdperkin"
REPO_NAME="nhl-scrabble"
IMAGE_NAME="nhl-scrabble-playwright"
REGISTRY="ghcr.io"
IMAGE_TAG="${IMAGE_TAG:-latest}"
DATE_TAG="$(date +%Y-%m-%d)"

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

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

log() {
    local color="$1"
    shift
    echo -e "${color}[build-playwright-image]${NC} $*"
}

# Parse arguments
PUSH=false
TEST=false

for arg in "$@"; do
    case "$arg" in
        --push)
            PUSH=true
            ;;
        --test)
            TEST=true
            ;;
        --help|-h)
            cat <<EOF
Build and optionally push the custom Playwright Docker image

Usage:
  $0 [OPTIONS]

Options:
  --push    Build and push to GitHub Container Registry
  --test    Build and run basic tests
  --help    Show this help message

Environment Variables:
  GITHUB_TOKEN    GitHub Personal Access Token (required for --push)
  IMAGE_TAG       Custom tag (default: latest)

Examples:
  # Build locally
  $0

  # Build and push to GHCR
  GITHUB_TOKEN=\$GH_TOKEN $0 --push

  # Build and test locally
  $0 --test

  # Build with custom tag
  IMAGE_TAG=dev $0
EOF
            exit 0
            ;;
        *)
            log "${RED}" "Unknown argument: $arg"
            log "${YELLOW}" "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Check if Docker is available
if ! command -v docker &> /dev/null; then
    log "${RED}" "ERROR: Docker is not installed or not in PATH"
    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

# Full image references
LOCAL_IMAGE="${IMAGE_NAME}:${IMAGE_TAG}"
GHCR_IMAGE_LATEST="${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:latest"
GHCR_IMAGE_DATE="${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:${DATE_TAG}"
GHCR_IMAGE_TAG="${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:${IMAGE_TAG}"

# Build image
log "${BLUE}" "Building Docker image..."
log "${BLUE}" "Image: ${LOCAL_IMAGE}"
log "${BLUE}" "Dockerfile: ${REPO_ROOT}/.docker/Dockerfile"

if ! docker build \
    -f "${REPO_ROOT}/.docker/Dockerfile" \
    -t "${LOCAL_IMAGE}" \
    -t "${GHCR_IMAGE_LATEST}" \
    -t "${GHCR_IMAGE_DATE}" \
    "${REPO_ROOT}"; then
    log "${RED}" "ERROR: Docker build failed"
    exit 1
fi

log "${GREEN}" "Image built successfully: ${LOCAL_IMAGE}"

# Test image if requested
if [[ "${TEST}" == "true" ]]; then
    log "${BLUE}" "Testing image..."

    # Test 1: Check Playwright version
    log "${BLUE}" "Test 1: Checking Playwright version..."
    if ! docker run --rm "${LOCAL_IMAGE}" playwright --version; then
        log "${RED}" "ERROR: Playwright version check failed"
        exit 1
    fi

    # Test 2: Check Python version
    log "${BLUE}" "Test 2: Checking Python version..."
    if ! docker run --rm "${LOCAL_IMAGE}" python --version; then
        log "${RED}" "ERROR: Python version check failed"
        exit 1
    fi

    # Test 3: Check browsers installed
    log "${BLUE}" "Test 3: Checking installed browsers..."
    if ! docker run --rm "${LOCAL_IMAGE}" \
        bash -c "playwright install --dry-run chromium 2>&1 | grep -q 'Playwright build.*is already installed'"; then
        log "${YELLOW}" "WARNING: Browser installation check returned unexpected result"
        log "${YELLOW}" "This may be normal - browsers might be installed but not in expected cache location"
    fi

    log "${GREEN}" "All tests passed!"
fi

# Push to GHCR if requested
if [[ "${PUSH}" == "true" ]]; then
    # Check for GitHub token
    if [[ -z "${GITHUB_TOKEN:-}" ]]; then
        log "${RED}" "ERROR: GITHUB_TOKEN environment variable required for push"
        log "${YELLOW}" "Set GITHUB_TOKEN to your GitHub Personal Access Token"
        log "${YELLOW}" "Token needs 'write:packages' scope"
        exit 1
    fi

    log "${BLUE}" "Logging in to GitHub Container Registry..."
    if ! echo "${GITHUB_TOKEN}" | docker login "${REGISTRY}" \
        -u "${REPO_OWNER}" --password-stdin; then
        log "${RED}" "ERROR: Failed to login to GHCR"
        exit 1
    fi

    log "${BLUE}" "Pushing image to GHCR..."

    # Push all tags
    for image in "${GHCR_IMAGE_LATEST}" "${GHCR_IMAGE_DATE}"; do
        log "${BLUE}" "Pushing: ${image}"
        if ! docker push "${image}"; then
            log "${RED}" "ERROR: Failed to push ${image}"
            exit 1
        fi
    done

    # Push custom tag if not 'latest'
    if [[ "${IMAGE_TAG}" != "latest" ]]; then
        log "${BLUE}" "Pushing: ${GHCR_IMAGE_TAG}"
        docker tag "${LOCAL_IMAGE}" "${GHCR_IMAGE_TAG}"
        if ! docker push "${GHCR_IMAGE_TAG}"; then
            log "${RED}" "ERROR: Failed to push ${GHCR_IMAGE_TAG}"
            exit 1
        fi
    fi

    log "${GREEN}" "Image pushed successfully to GHCR"
    log "${GREEN}" "Available at:"
    log "${GREEN}" "  - ${GHCR_IMAGE_LATEST}"
    log "${GREEN}" "  - ${GHCR_IMAGE_DATE}"
    if [[ "${IMAGE_TAG}" != "latest" ]]; then
        log "${GREEN}" "  - ${GHCR_IMAGE_TAG}"
    fi
fi

# Summary
log "${GREEN}" "Build complete!"
log "${BLUE}" "Local image: ${LOCAL_IMAGE}"
log "${BLUE}" "Size: $(docker images --format '{{.Size}}' "${LOCAL_IMAGE}")"

# Show usage example
cat <<EOF

${GREEN}Usage Examples:${NC}

  # Test locally-built image
  PLAYWRIGHT_IMAGE=${LOCAL_IMAGE} ./scripts/playwright --version

  # Run tests with locally-built image
  PLAYWRIGHT_IMAGE=${LOCAL_IMAGE} ./scripts/pytest-playwright qa/web/tests/visual/

  # Pull from GHCR (after push)
  docker pull ${GHCR_IMAGE_LATEST}
EOF
