/**
 * Copyright (c) 2022, 2026 Joerg Breitbart
 * @license MIT
 */

import * as path from 'node:path';
import * as fs from 'node:fs';
import * as cp from 'node:child_process';
import { rmFolder } from '../helper.js';

import { APP_ROOT, PROJECT_ROOT, CONFIG, SHELL, isPosix, getSdkRoot } from '../config.js';


/**
 * Get the path to the emscripten SDK.
 * The call evals the config settings and may try to install
 * the SDK as stated from the config.
 */
// FIXME: make it possible to activate a different version once installed
// FIXME: make 'latest' somehow updateable
export function getEmscriptenPath(): string {
  const emsdkConf = CONFIG.emsdk as any;
  if (emsdkConf && emsdkConf.hasOwnProperty('path')) {
    // from preinstalled
    return emsdkConf.path;
  }

  // from autoinstalled
  const root = getSdkRoot(emsdkConf.store);
  const basePath = path.join(root, 'inwasm-sdks', 'emsdk');
  if (fs.existsSync(basePath) && fs.existsSync(path.join(basePath, 'emsdk.py'))) {
    return basePath;
  }
  rmFolder(basePath);

  // install
  fs.mkdirSync(path.dirname(basePath), { recursive: true });
  console.log(`\n[emscripten.checkout] Cloning emscripten...`);
  cp.execSync(`git clone https://github.com/emscripten-core/emsdk.git ${basePath}`, {shell: SHELL, stdio: 'inherit'});
  console.log(`\n[emscripten.version] Activate version: "${emsdkConf.version}"`);
  cp.execSync(
    `${basePath}/emsdk install ${emsdkConf.version} && ${basePath}/emsdk activate ${emsdkConf.version}`,
    {shell: SHELL, stdio: 'inherit'}
  );

  return basePath;
}


/**
 * Return the bin/ path of the embedded clang version.
 */
export function getClangBinPath(): string {
  return path.join(getEmscriptenPath(), 'upstream', 'bin');
}


/**
 * Run the given command in the emscripten env.
 * 
 * Commands like `emcc` can be used directly (implicitly added to PATH by env script).
 * To run executables of the embedded clang version, use `getClangBinPath()` to get a
 * hold of clang's bin/ folder.
 */
export function emscriptenRun(cmd: string) {
  const sdkPath = getEmscriptenPath();
  const sdk = isPosix
    ? `source ${path.join(sdkPath, 'emsdk_env.sh')} > /dev/null 2>&1`
    : `${path.join(sdkPath, 'emsdk_env.bat')} >nul 2>&1`;
  cp.execSync(`${sdk} && ${cmd}`, {shell: SHELL, stdio: 'inherit'});
}
