/**
 * @file Playwright configuration for Visual Regression Testing.
 * @description Configures Playwright for VRT comparing Drupal SDC components
 * against the upstream @kern-ux/native reference implementation.
 *
 * This configuration:
 * - Serves both Storybook (Drupal SDC) and Reference (KERN-UX native)
 * - Configures visual comparison thresholds
 * - Sets up multiple browser and theme projects
 * - Manages snapshot storage and artifact output
 *
 * Environment Variables:
 * - VRT_REFERENCE=true: Include reference Storybook server (for baseline capture)
 */

import { defineConfig, devices } from "@playwright/test";
import * as fs from "fs";
import * as path from "path";

/** Storybook server port (Drupal SDC components) - using dev server for now */
const STORYBOOK_PORT = 6006;

/** Reference server port (KERN-UX native reference) */
const REFERENCE_PORT = 6008;

/** Check if reference Storybook exists and is requested */
const REFERENCE_DIR = path.join(__dirname, "tests", "vrt", "reference-storybook");
const USE_REFERENCE_SERVER = process.env.VRT_REFERENCE === "true" && fs.existsSync(REFERENCE_DIR);

// Log server configuration for debugging
console.log("[VRT Config] VRT_REFERENCE:", process.env.VRT_REFERENCE);
console.log("[VRT Config] Reference directory exists:", fs.existsSync(REFERENCE_DIR));
console.log("[VRT Config] USE_REFERENCE_SERVER:", USE_REFERENCE_SERVER);

/** Visual comparison thresholds */
const VISUAL_COMPARISON_CONFIG = {
  /** Maximum ratio of different pixels (0.02 = 2%) */
  maxDiffPixelRatio: 0.02,
  /** Per-pixel color difference threshold (0-1 scale) */
  threshold: 0.3,
};

export default defineConfig({
  /** Directory containing test files */
  testDir: "./tests/vrt",

  /** Pattern to match test files */
  testMatch: "**/*.spec.ts",

  /** Run tests in parallel for faster execution */
  fullyParallel: true,

  /** Fail the build on CI if test.only is accidentally left in */
  forbidOnly: Boolean(process.env.CI),

  /** Retry failed tests in CI for flakiness detection */
  retries: process.env.CI ? 2 : 0,

  /** Number of parallel workers - limit on CI for stability */
  workers: process.env.CI ? 2 : undefined,

  /** HTML reporter for detailed test results */
  reporter: process.env.CI
    ? [
        ["dot"],
        ["html", { outputFolder: "playwright-report", open: "never" }],
        ["junit", { outputFile: "test-results/playwright.xml" }],
      ]
    : [
        ["list", { printSteps: true }],
        ["html"],
      ],

  /** Shared settings for all projects */
  use: {
    /** Collect trace on first retry for debugging */
    trace: "on-first-retry",

    /** Take screenshot on failure */
    screenshot: "only-on-failure",

    /** Timeout for actions like click, fill, etc. */
    actionTimeout: 10000,

    /** Timeout for navigation */
    navigationTimeout: 30000,
  },

  /** Visual comparison settings applied globally */
  expect: {
    toHaveScreenshot: {
      maxDiffPixelRatio: VISUAL_COMPARISON_CONFIG.maxDiffPixelRatio,
      threshold: VISUAL_COMPARISON_CONFIG.threshold,
      animations: "disabled",
    },
    toMatchSnapshot: {
      maxDiffPixelRatio: VISUAL_COMPARISON_CONFIG.maxDiffPixelRatio,
      threshold: VISUAL_COMPARISON_CONFIG.threshold,
    },
  },

  /** Snapshot output configuration - flat directory with custom names */
  snapshotDir: "./tests/vrt/snapshots",
  snapshotPathTemplate: "{snapshotDir}/{arg}{ext}",

  /** Test timeout - allow time for servers to respond */
  timeout: 60000,

  /** Configure projects for different browsers and themes */
  projects: [
    // Main compliance testing projects (compare Drupal SDC against KERN-UX baselines)
    {
      name: "chromium-light",
      use: {
        ...devices["Desktop Chrome"],
        baseURL: `http://localhost:${STORYBOOK_PORT}`,
      },
      metadata: {
        theme: "light",
      },
    },
    // TODO: Dark mode tests disabled - reference Storybook theme switching not working
    // The KERN-UX reference Storybook doesn't properly respond to theme URL parameters.
    // Re-enable when upstream fixes theme handling or we find a workaround.
    // {
    //   name: "chromium-dark",
    //   use: {
    //     ...devices["Desktop Chrome"],
    //     baseURL: `http://localhost:${STORYBOOK_PORT}`,
    //   },
    //   metadata: {
    //     theme: "dark",
    //   },
    // },
    // Baseline capture projects (capture screenshots from KERN-UX reference)
    {
      name: "baseline-light",
      use: {
        ...devices["Desktop Chrome"],
        baseURL: `http://localhost:${REFERENCE_PORT}`,
      },
      metadata: {
        theme: "light",
      },
    },
    // TODO: Dark mode baseline disabled - reference Storybook theme switching not working
    // {
    //   name: "baseline-dark",
    //   use: {
    //     ...devices["Desktop Chrome"],
    //     baseURL: `http://localhost:${REFERENCE_PORT}`,
    //   },
    //   metadata: {
    //     theme: "dark",
    //   },
    // },
  ],

  /** Web servers configuration - conditionally include reference server */
  webServer: [
    {
      command: `npm run storybook -- --ci -p ${STORYBOOK_PORT}`,
      url: `http://localhost:${STORYBOOK_PORT}`,
      /** Reuse existing server if running, otherwise start a new one */
      reuseExistingServer: true,
      timeout: 120000,
      /** Ensure stdout/stderr are shown for debugging startup issues */
      stdout: "pipe",
      stderr: "pipe",
    },
    // Reference server only started when VRT_REFERENCE=true and directory exists
    ...(USE_REFERENCE_SERVER
      ? [
        {
          command: `npx serve tests/vrt/reference-storybook -l ${REFERENCE_PORT} --no-clipboard --cors`,
          url: `http://localhost:${REFERENCE_PORT}`,
          reuseExistingServer: !process.env.CI,
          timeout: 120000,
        },
      ]
      : []),
  ],

  /** Output directory for test artifacts */
  outputDir: "test-results",
});
