import { remote, type Browser } from "webdriverio";
import { getCapabilities } from "../config/capabilities";

let driver: Browser | null = null;

const APPIUM_HOST = process.env.APPIUM_HOST || "localhost";
const APPIUM_PORT = parseInt(process.env.APPIUM_PORT || "4723", 10);

/**
 * Initialize the Appium driver. If already initialized, returns the existing instance.
 * With --runInBand, all test files share this singleton.
 */
export async function initDriver(): Promise<Browser> {
  if (driver) return driver;

  const capabilities = getCapabilities();

  driver = await remote({
    hostname: APPIUM_HOST,
    port: APPIUM_PORT,
    path: "/",
    capabilities,
    logLevel: "warn",
  });

  return driver;
}

export function getDriver(): Browser {
  if (!driver) {
    throw new Error("Driver not initialized. Call initDriver() first.");
  }
  return driver;
}

export async function quitDriver(): Promise<void> {
  if (driver) {
    await driver.deleteSession();
    driver = null;
  }
}
