import { defineConfig, devices } from '@playwright/test';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';

// Live config: runs E2E tests against https://dev.multi.deal
// Requires ALLOW_LIVE_E2E=1 env var (enforced by _live-guard.mjs in each spec).
// No webServer block — tests hit the already-deployed Worker directly.

function parseEnvFile(content: string): Record<string, string> {
  const vars: Record<string, string> = {};
  for (const line of content.split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eq = trimmed.indexOf('=');
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq).trim();
    const val = trimmed
      .slice(eq + 1)
      .trim()
      .replace(/^["']|["']$/g, '');
    vars[key] = val;
  }
  return vars;
}

function loadEnvFile(path: string): Record<string, string> {
  if (!existsSync(path)) return {};
  return parseEnvFile(readFileSync(path, 'utf8'));
}

const configDir = new URL('.', import.meta.url).pathname;

// Load local env files without overriding explicit shell controls such as live-E2E opt-in.
const fileEnv = {
  ...loadEnvFile(join(configDir, '.env')),
  ...loadEnvFile(join(configDir, '.dev.vars')),
};
for (const [key, value] of Object.entries(fileEnv)) {
  if (process.env[key] === undefined) process.env[key] = value;
}

// auth-helper.ts derives cookie domain from BASE_URL — must match live host.
process.env.BASE_URL = 'https://dev.multi.deal';

export default defineConfig({
  testDir: './tests',
  // tests/waveb runs standalone via tests/waveb/playwright.config.ts.
  testIgnore: '**/waveb/**',
  snapshotDir: './test-artifacts/visual-regression/screenshots',
  fullyParallel: false,
  forbidOnly: false,
  retries: 2,
  workers: 1,
  reporter: 'line',
  use: {
    baseURL: 'https://dev.multi.deal',
    serviceWorkers: 'block',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    locale: 'he-IL',
    timezoneId: 'Asia/Jerusalem',
  },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
  // No webServer — tests run against the live deployed Worker
});
