#!/usr/bin/env bash
# Regenerate Playwright visual regression snapshots.
# - In the devcontainer (Playwright Noble): same image as CI, snapshot matches CI.
# - When Docker is available on host: runs in the same image as CI for a CI-accurate baseline.
# - Otherwise: run the update-e2e-snapshots workflow in Woodpecker (manual pipeline).
set -e

SCRIPT_DIR="${BASH_SOURCE%/*}"
PROJECT_ROOT="${SCRIPT_DIR}/.."
cd "$PROJECT_ROOT"
PROJECT_ROOT="$(pwd)"

if command -v docker >/dev/null 2>&1; then
    PLAYWRIGHT_IMAGE="${PLAYWRIGHT_IMAGE:-mcr.microsoft.com/playwright:v1.58.0-noble}"
    echo "Using Docker image: $PLAYWRIGHT_IMAGE (same as CI)"
    echo "Project root: $PROJECT_ROOT"
    echo ""

    docker run --rm \
      -v "$PROJECT_ROOT:/app" -w /app \
      -e CI=1 \
      "$PLAYWRIGHT_IMAGE" \
      bash -c '
        corepack enable && corepack prepare pnpm@10.28.2 --activate
        pnpm install --frozen-lockfile || pnpm install
        pnpm run build
        npx serve dist -p 4173 &
        sleep 2
        pnpm exec playwright test --update-snapshots
      '
    pnpm install --config.confirmModulesPurge=false
else
    echo "Updating snapshots in the current environment (matches CI when using the devcontainer)."
    echo ""

    pnpm run build

    # Unset CI so Playwright config starts the preview server
    unset CI
    pnpm exec playwright test --update-snapshots
fi

echo ""
echo "Snapshots updated. Commit the changed files under tests/visual.spec.ts-snapshots/ if needed."
