import os from "node:os";
import path from "node:path";
import { spawn, type ChildProcess } from "node:child_process";
import fs from "node:fs";

let tauriDriver: ChildProcess;

export const config: WebdriverIO.Config = {
  specs: ["./e2e/specs/**/*.e2e.ts"],
  exclude: [],

  // Run tests sequentially to avoid session conflicts
  maxInstances: 1,

  port: 4444, // tauri-driver default port
  hostname: "localhost",

  capabilities: [
    {
      maxInstances: 1,
      "tauri:options": {
        application: getTauriApplicationPath(),
        // Use a separate test data directory
        env: {
          JELLYTAU_DATA_DIR: path.join(os.tmpdir(), "jellytau-test-data"),
        },
      },
    } as WebdriverIO.Capabilities,
  ],

  logLevel: "warn", // Reduce log noise
  bail: 0,
  waitforTimeout: 10000,
  connectionRetryTimeout: 120000,
  connectionRetryCount: 3,

  framework: "mocha",
  reporters: ["spec"],

  mochaOpts: {
    ui: "bdd",
    timeout: 60000,
  },

  // Start tauri-driver before session
  onPrepare: async function () {
    tauriDriver = spawn(
      path.resolve(os.homedir(), ".cargo", "bin", "tauri-driver"),
      [],
      { stdio: [null, process.stdout, process.stderr] }
    );

    return new Promise((resolve) => {
      setTimeout(resolve, 1000); // Give tauri-driver time to start
    });
  },

  // Clean up tauri-driver after session
  onComplete: async function () {
    tauriDriver.kill();
  },
};

function getTauriApplicationPath(): string {
  const platform = process.platform;
  const cwd = process.cwd();

  // Check for release build first, fallback to debug
  if (platform === "win32") {
    const releasePath = path.join(cwd, "src-tauri/target/release/jellytau.exe");
    const debugPath = path.join(cwd, "src-tauri/target/debug/jellytau.exe");
    if (fs.existsSync(releasePath)) return releasePath;
    if (fs.existsSync(debugPath)) return debugPath;
    return releasePath; // Return default if neither exists
  } else if (platform === "darwin") {
    const releasePath = path.join(cwd, "src-tauri/target/release/bundle/macos/jellytau.app");
    const debugPath = path.join(cwd, "src-tauri/target/debug/bundle/macos/jellytau.app");
    if (fs.existsSync(releasePath)) return releasePath;
    if (fs.existsSync(debugPath)) return debugPath;
    return releasePath;
  } else {
    // Linux
    const releasePath = path.join(cwd, "src-tauri/target/release/jellytau");
    const debugPath = path.join(cwd, "src-tauri/target/debug/jellytau");
    if (fs.existsSync(releasePath)) return releasePath;
    if (fs.existsSync(debugPath)) return debugPath;
    return debugPath; // Return debug path as default for Linux
  }
}
