// *****************************************************************************
// Copyright (C) 2026 EclipseSource and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

/**
 * Script for tests: creates a `BackendApplication`, which installs its process handlers, starts a
 * child process, prints the PID of the child and exits with code {@link EXITING_BACKEND_EXIT_CODE}.
 * The `exit` handler of the `BackendApplication` then terminates the process tree.
 * Set {@link EXITING_BACKEND_NO_POWERSHELL} to make the listing of the children of the process fail.
 * Set {@link EXITING_BACKEND_GRACEFUL} to shut down as on `SIGTERM` instead, which exits with code 1.
 */

import 'reflect-metadata';
import * as cp from 'child_process';
import * as path from 'path';
import { Container } from 'inversify';
import { bindContributionProvider, ILogger, Stopwatch } from '../../common/index.js';
import { MockLogger } from '../../common/test/mock-logger.js';
import {
    BackendApplication, BackendApplicationCliContribution, BackendApplicationContribution, EarlyExpressMiddleware, RootContainer
} from '../backend-application.js';
import { NodeStopwatch } from '../performance/node-stopwatch.js';
import { ProcessUtils } from '../process-utils.js';

export const EXITING_BACKEND_EXIT_CODE = 3;

/**
 * Environment variable that makes PowerShell unrunnable for the {@link ProcessUtils} of the script.
 */
export const EXITING_BACKEND_NO_POWERSHELL = 'THEIA_TEST_EXITING_BACKEND_NO_POWERSHELL';

/**
 * Environment variable that makes the script shut down gracefully, as on `SIGTERM`, rather than exit abruptly.
 */
export const EXITING_BACKEND_GRACEFUL = 'THEIA_TEST_EXITING_BACKEND_GRACEFUL';

class NoPowerShellProcessUtils extends ProcessUtils {
    protected override winGetPowerShellPath(): string {
        return 'C:\\does-not-exist\\powershell.exe';
    }
}

// The equivalent of `require.main === module` for an ES module.
if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) {
    const container = new Container();
    container.bind(RootContainer).toConstantValue(container);
    container.bind(ILogger).to(MockLogger).inSingletonScope();
    container.bind(Stopwatch).to(NodeStopwatch).inSingletonScope();
    container.bind(ProcessUtils).to(process.env[EXITING_BACKEND_NO_POWERSHELL] ? NoPowerShellProcessUtils : ProcessUtils).inSingletonScope();
    container.bind(BackendApplicationCliContribution).toSelf().inSingletonScope();
    container.bind(EarlyExpressMiddleware).toSelf().inSingletonScope();
    bindContributionProvider(container, BackendApplicationContribution);
    container.bind(BackendApplication).toSelf().inSingletonScope();
    container.get(BackendApplication);

    const child = cp.spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });
    child.on('spawn', () => process.stdout.write(`${child.pid}\n`, () => {
        if (process.env[EXITING_BACKEND_GRACEFUL]) {
            // Signals cannot be sent to a process on Windows, so invoke the handler of the `BackendApplication` directly.
            process.emit('SIGTERM', 'SIGTERM');
        } else {
            process.exit(EXITING_BACKEND_EXIT_CODE);
        }
    }));
}
