/**
 * WebDriverIO configuration for Electrobun E2E tests.
 *
 * Electrobun uses WebKitGTK under the hood on Linux — we drive it via
 * WebDriver (same as Tauri's approach with tauri-driver).
 * Port 9760 matches our Vite dev port convention.
 */

import { execSync } from "node:child_process";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { existsSync } from "node:fs";
import { createTestFixture } from "./fixtures.ts";

const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = resolve(__dirname, "../..");

// Electrobun built binary path (canary build output)
const electrobunBinary = resolve(projectRoot, "build/Agent Orchestrator");

// Test fixture — isolated config/data dirs
const fixture = createTestFixture("agor-ebun-e2e");

process.env.AGOR_TEST = "1";
process.env.AGOR_TEST_DATA_DIR = fixture.dataDir;
process.env.AGOR_TEST_CONFIG_DIR = fixture.configDir;

const WEBDRIVER_PORT = 9761;

console.log(`Test fixture created at ${fixture.rootDir}`);

export const config = {
  // ── Runner ──
  runner: "local",
  maxInstances: 1,

  // ── Connection ──
  hostname: "localhost",
  port: WEBDRIVER_PORT,
  path: "/",

  // ── Specs ──
  specs: [
    resolve(__dirname, "specs/splash.test.ts"),
    resolve(__dirname, "specs/smoke.test.ts"),
    resolve(__dirname, "specs/groups.test.ts"),
    resolve(__dirname, "specs/settings.test.ts"),
    resolve(__dirname, "specs/theme.test.ts"),
    resolve(__dirname, "specs/terminal.test.ts"),
    resolve(__dirname, "specs/agent.test.ts"),
    resolve(__dirname, "specs/keyboard.test.ts"),
    resolve(__dirname, "specs/search.test.ts"),
    resolve(__dirname, "specs/notifications.test.ts"),
    resolve(__dirname, "specs/files.test.ts"),
    resolve(__dirname, "specs/comms.test.ts"),
    resolve(__dirname, "specs/tasks.test.ts"),
    resolve(__dirname, "specs/diagnostics.test.ts"),
  ],

  // ── Capabilities ──
  capabilities: [
    {
      "wdio:enforceWebDriverClassic": true,
      browserName: "webkit",
    },
  ],

  // ── Framework ──
  framework: "mocha",
  mochaOpts: {
    ui: "bdd",
    timeout: 120_000,
  },

  // ── Reporter ──
  reporters: ["spec"],

  // ── Logging ──
  logLevel: "warn",

  // ── Timeouts ──
  waitforTimeout: 10_000,
  connectionRetryTimeout: 30_000,
  connectionRetryCount: 3,

  // ── Hooks ──

  onPrepare() {
    if (!existsSync(electrobunBinary) && !process.env.SKIP_BUILD) {
      console.log("Building Electrobun canary...");
      execSync("vite build && electrobun build --env=canary", {
        cwd: projectRoot,
        stdio: "inherit",
      });
    }

    if (!existsSync(electrobunBinary)) {
      throw new Error(
        `Electrobun binary not found at ${electrobunBinary}. ` +
          "Run 'bun run build:canary' first.",
      );
    }
  },

  afterSession() {
    fixture.cleanup();
    console.log("Test fixture cleaned up.");
  },
};
