'use strict';

const { spawn } = require('child_process');
const path = require('path');

const { resolveAndroidStudioPath } = require('./resolve-android-studio-path');

function main() {
  const studioPath = resolveAndroidStudioPath();

  if (!studioPath) {
    console.error(
      '[error] Unable to locate Android Studio (studio.sh).\n'
        + '        Install Android Studio or set CAPACITOR_ANDROID_STUDIO_PATH to studio.sh.'
    );
    process.exit(1);
  }

  const tojuAppDir = path.resolve(__dirname, '..', 'toju-app');
  const child = spawn('npx', ['cap', 'open', 'android'], {
    cwd: tojuAppDir,
    env: {
      ...process.env,
      CAPACITOR_ANDROID_STUDIO_PATH: studioPath
    },
    stdio: 'inherit',
    shell: process.platform === 'win32'
  });

  child.on('error', (error) => {
    console.error(error instanceof Error ? error.message : String(error));
    process.exit(1);
  });

  child.on('exit', (code, signal) => {
    if (signal) {
      process.kill(process.pid, signal);
      return;
    }

    process.exit(code ?? 0);
  });
}

main();
