'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');
const { test } = require('node:test');
const assert = require('node:assert/strict');

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

test('resolveAndroidStudioPath prefers CAPACITOR_ANDROID_STUDIO_PATH when executable', () => {
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-sh-'));
  const studioSh = path.join(tempDir, 'studio.sh');

  fs.writeFileSync(studioSh, '#!/bin/sh\n', { mode: 0o755 });

  const resolved = resolveAndroidStudioPath({
    env: { CAPACITOR_ANDROID_STUDIO_PATH: studioSh },
    homeDir: tempDir
  });

  assert.equal(resolved, studioSh);

  fs.rmSync(tempDir, { recursive: true, force: true });
});

test('resolveAndroidStudioPath finds flatpak active studio.sh when present', () => {
  const flatpakPath =
    '/var/lib/flatpak/app/com.google.AndroidStudio/x86_64/stable/active/files/extra/bin/studio.sh';

  if (!fs.existsSync(flatpakPath)) {
    return;
  }

  const resolved = resolveAndroidStudioPath({
    env: {},
    homeDir: '/nonexistent-home-for-test'
  });

  assert.equal(resolved, flatpakPath);
});
