export type AppiumCapabilities = Record<string, unknown>;

const COMMON_CAPABILITIES: AppiumCapabilities = {
  platformName: "Android",
  "appium:automationName": "UiAutomator2",
  "appium:deviceName": process.env.DEVICE_NAME || "emulator-5554",
  "appium:autoGrantPermissions": true,
  "appium:newCommandTimeout": 300,
};

/**
 * Dev Client mode: app is already installed via `expo start --android`.
 * Appium connects to the running app without reinstalling.
 */
const DEV_CLIENT_CAPABILITIES: AppiumCapabilities = {
  ...COMMON_CAPABILITIES,
  "appium:appPackage": "host.exp.exponent",
  "appium:appActivity": ".experience.ExperienceActivity",
  "appium:noReset": true,
};

/**
 * APK mode: Appium installs the APK directly.
 * Used in CI where the APK is built via `eas build --profile e2e`.
 */
function getApkCapabilities(apkPath: string): AppiumCapabilities {
  return {
    ...COMMON_CAPABILITIES,
    "appium:app": apkPath,
    "appium:noReset": false,
  };
}

/**
 * Returns the appropriate capabilities based on the APK_PATH env variable.
 * - APK_PATH set → APK mode (CI)
 * - APK_PATH not set → Dev Client mode (local development)
 */
export function getCapabilities(): AppiumCapabilities {
  const apkPath = process.env.APK_PATH;

  if (apkPath) {
    console.log(`[Appium] APK mode: ${apkPath}`);
    return getApkCapabilities(apkPath);
  }

  console.log("[Appium] Dev Client mode");
  return DEV_CLIENT_CAPABILITIES;
}
