"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Electron = void 0;
const compare_versions_1 = require("compare-versions");
const Logger_1 = require("./Logger");
const node_child_process_1 = require("node:child_process");
const node_path_1 = __importDefault(require("node:path"));
const Process_1 = require("./Process");
const IocdWdioServiceError_1 = require("../../utils/error/IocdWdioServiceError");
const ELECTRON_HEADERS_URL = 'https://electronjs.org/headers/index.json';
/**
 * Utilities for working with the Electron runtime in tests.
 *
 * These helpers allow the service to resolve the correct ChromeDriver version
 * and to start either a source build or a packaged binary of IO.Connect Desktop.
 */
class Electron {
    static async getChromiumVersion(electronVersion) {
        const response = await fetch(ELECTRON_HEADERS_URL);
        const versions = await response.json();
        versions.sort((a, b) => (0, compare_versions_1.compareVersions)(a.version, b.version));
        const match = versions.find(v => v.version === electronVersion || v.version.startsWith(electronVersion + '.'));
        if (!match?.chrome) {
            throw new IocdWdioServiceError_1.IocdWdioServiceError(`Unable to find chromium version for electronVersion: ${electronVersion}.`);
        }
        return match?.chrome;
    }
    static getMajor(version) {
        return version.split('.')[0];
    }
    /**
     * Spawns the Electron platform from source (compiled JavaScript) and returns the ChildProcess.
     *
     * - Runs the compiled JS entry (e.g. app/main.js) with --inspect for debugging
     * - Relies on emitted source maps for TypeScript breakpoints (no ts-node preload)
     * - Mirrors VS Code’s “Run/Debug” behavior after a build has been done
     */
    static spawnFromSource(cwdPathAbsolute, entry, // e.g. './app/main.js'
    startArgs, enableLogging = false, inspectPort = null) {
        const env = { ...process.env };
        // Remove inherited Node flags (like ts-node preload or extra inspectors)
        delete env.NODE_OPTIONS;
        const electronBin = node_path_1.default.join(cwdPathAbsolute, 'node_modules', 'electron', 'dist', 'electron.exe');
        this.logger.info('Spawning Electron app (compiled JS):', electronBin, `inspect-brk=${inspectPort}`, `cwd=${cwdPathAbsolute}`, `entry=${entry}`, `args=${startArgs.join(' ')}`);
        let nodeArgs = [];
        if (inspectPort) {
            nodeArgs = [
                '--nolazy',
                `--inspect-brk=${inspectPort}`, // enable Node inspector, break on first line
            ];
        }
        // Electron executes built JS, breakpoints rely on source maps
        const proc = (0, node_child_process_1.spawn)(electronBin, [...nodeArgs, entry, ...startArgs], {
            cwd: cwdPathAbsolute,
            shell: false,
            env: {
                ...env,
                NODE_ENV: 'development',
            },
            stdio: enableLogging ? 'inherit' : Process_1.Process.defaultStdio,
        });
        if (!enableLogging) {
            Process_1.Process.ignoreOutput(proc);
        }
        return proc;
    }
    /**
     * Spawn the platform from exe and return the ChildProcess
     */
    static spawnFromExe(binaryPathAbsolute, execArgs, enableLogging = false) {
        this.logger.info('Spawning the electron app from exe:', binaryPathAbsolute, execArgs);
        const proc = (0, node_child_process_1.spawn)(binaryPathAbsolute, execArgs, {
            stdio: enableLogging ? 'inherit' : Process_1.Process.defaultStdio,
            shell: false,
            windowsHide: false,
        });
        // ignore logs form a spawned process
        // if the logs buffers are not handled, the platform wont be able to start
        if (!enableLogging) {
            Process_1.Process.ignoreOutput(proc);
        }
        return proc;
    }
}
exports.Electron = Electron;
Electron.logger = (0, Logger_1.Logger)('system/Electron');
