'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

/**
 * @param {string} filePath
 * @returns {boolean}
 */
function isExecutableStudioSh(filePath) {
  try {
    const stat = fs.statSync(filePath);

    return stat.isFile() && (stat.mode & 0o111) !== 0;
  } catch {
    return false;
  }
}

/**
 * @param {string} homeDir
 * @returns {string | null}
 */
function findJetBrainsToolboxStudioSh(homeDir) {
  const toolboxRoot = path.join(
    homeDir,
    '.local/share/JetBrains/Toolbox/apps/AndroidStudio'
  );

  let entries;

  try {
    entries = fs.readdirSync(toolboxRoot, { withFileTypes: true });
  } catch {
    return null;
  }

  const studioPaths = entries
    .filter((entry) => entry.isDirectory())
    .map((entry) => path.join(toolboxRoot, entry.name, 'bin/studio.sh'))
    .filter((candidate) => isExecutableStudioSh(candidate))
    .sort();

  return studioPaths.at(-1) ?? null;
}

/**
 * @param {{ env?: NodeJS.ProcessEnv; homeDir?: string }} [options]
 * @returns {string | null}
 */
function resolveAndroidStudioPath(options = {}) {
  const env = options.env ?? process.env;
  const homeDir = options.homeDir ?? os.homedir();

  const fromEnv = String(env.CAPACITOR_ANDROID_STUDIO_PATH ?? '').trim();

  if (fromEnv && isExecutableStudioSh(fromEnv)) {
    return fromEnv;
  }

  const candidates = [
    '/usr/local/android-studio/bin/studio.sh',
    '/opt/android-studio/bin/studio.sh',
    path.join(homeDir, 'android-studio/bin/studio.sh'),
    '/var/lib/flatpak/app/com.google.AndroidStudio/x86_64/stable/active/files/extra/bin/studio.sh',
    path.join(
      homeDir,
      '.local/share/flatpak/app/com.google.AndroidStudio/x86_64/stable/active/files/extra/bin/studio.sh'
    ),
    '/snap/android-studio/current/bin/studio.sh'
  ];

  for (const candidate of candidates) {
    if (isExecutableStudioSh(candidate)) {
      return candidate;
    }
  }

  return findJetBrainsToolboxStudioSh(homeDir);
}

module.exports = {
  resolveAndroidStudioPath,
  isExecutableStudioSh
};

if (require.main === module) {
  const resolved = resolveAndroidStudioPath();

  if (!resolved) {
    console.error(
      'Could not find Android Studio (studio.sh). Install Android Studio or set CAPACITOR_ANDROID_STUDIO_PATH.'
    );
    process.exit(1);
  }

  process.stdout.write(`${resolved}\n`);
}
