import { Logger } from '../config/logger.js';
import { existsSync } from '../node-singletons/fs.js';
import * as path from '../node-singletons/path.js';
import { pathToFileURL } from '../node-singletons/url.js';
const getProjectRoot = () => {
    const fromEnv = process.env?.['ZINTRUST_PROJECT_ROOT'] ?? '';
    if (fromEnv.trim() !== '')
        return fromEnv.trim();
    return process.cwd();
};
const getBootstrapCandidates = (projectRoot) => [
    path.join(projectRoot, 'src', 'boot', 'bootstrap.ts'),
    path.join(projectRoot, 'dist', 'src', 'boot', 'bootstrap.js'),
    path.join(projectRoot, 'src', 'boot', 'bootstrap.js'),
];
const tryImportBootstrapCandidate = async (candidate) => {
    if (!existsSync(candidate))
        return false;
    try {
        await import(pathToFileURL(candidate).href);
        return true;
    }
    catch (error) {
        Logger.warn('Failed to import project bootstrap candidate', {
            candidate,
            error: error instanceof Error ? error.message : String(error),
        });
        return false;
    }
};
export async function loadProjectBootstrap() {
    const projectRoot = getProjectRoot();
    for (const candidate of getBootstrapCandidates(projectRoot)) {
        // eslint-disable-next-line no-await-in-loop
        const loaded = await tryImportBootstrapCandidate(candidate);
        if (loaded)
            return;
    }
    await import('../boot/bootstrap.js');
}
export default Object.freeze({
    loadProjectBootstrap,
});
