#!/usr/bin/env node

/**
 * Downloads demo APKs/apps for E2E testing.
 *
 * - Android: ApiDemos-debug.apk from appium/android-apidemos
 * - iOS: UIKitCatalog (built from Xcode sample project, or downloaded as .app.zip)
 */

import { createWriteStream, existsSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';

const __dirname = dirname(fileURLToPath(import.meta.url));
const APPS_DIR = join(__dirname, '..', 'apps');

const DOWNLOADS = [
  {
    name: 'ApiDemos-debug.apk',
    url: 'https://github.com/appium/android-apidemos/releases/download/v6.0.7/ApiDemos-debug.apk',
    platform: 'android',
  },
  {
    name: 'mda-2.2.0-25.apk',
    url: 'https://github.com/saucelabs/my-demo-app-android/releases/download/2.2.0/mda-2.2.0-25.apk',
    platform: 'android',
  },
];

async function downloadFile(url, destPath) {
  console.log(`  Downloading ${url} ...`);
  const response = await fetch(url, { redirect: 'follow' });
  if (!response.ok) {
    throw new Error(`Failed to download ${url}: HTTP ${response.status}`);
  }
  const nodeStream = Readable.fromWeb(response.body);
  const fileStream = createWriteStream(destPath);
  await pipeline(nodeStream, fileStream);
  console.log(`  Saved to ${destPath}`);
}

async function main() {
  mkdirSync(APPS_DIR, { recursive: true });

  console.log('TestRelic Appium Analytics — Downloading demo apps\n');

  for (const app of DOWNLOADS) {
    const destPath = join(APPS_DIR, app.name);
    if (existsSync(destPath)) {
      console.log(`  [${app.platform}] ${app.name} already exists, skipping.`);
      continue;
    }
    try {
      await downloadFile(app.url, destPath);
      console.log(`  [${app.platform}] ${app.name} downloaded successfully.\n`);
    } catch (err) {
      console.error(`  [${app.platform}] Failed to download ${app.name}: ${err.message}`);
      console.error(`  You can manually download from: ${app.url}\n`);
    }
  }

  console.log('\nDone. Apps are in:', APPS_DIR);
  console.log('\nNote: For iOS UICatalog, build from Xcode sample project on macOS:');
  console.log('  https://developer.apple.com/documentation/uikit/views_and_controls/uikit_catalog_creating_and_customizing_views_and_controls');
}

main().catch(console.error);
