import { spawn } from 'child_process';
let caffeinate = null;
/** macOS: `caffeinate -w <pid>` — Mac не уходит в сон, пока живёт bridge. */
export function startKeepAwake(enabled) {
    if (!enabled || process.platform !== 'darwin')
        return;
    if (caffeinate)
        return;
    try {
        caffeinate = spawn('caffeinate', ['-w', String(process.pid)], {
            stdio: 'ignore',
        });
        caffeinate.on('error', (err) => {
            console.warn(`[keep-awake] caffeinate error: ${err.message}`);
            caffeinate = null;
        });
        caffeinate.on('exit', (code, signal) => {
            if (code != null && code !== 0) {
                console.warn(`[keep-awake] caffeinate exited code=${code} signal=${signal ?? '-'}`);
            }
            caffeinate = null;
        });
        console.log('[keep-awake] macOS sleep prevention on (caffeinate -w bridge)');
    }
    catch (e) {
        console.warn(`[keep-awake] start failed: ${e.message}`);
    }
}
export function stopKeepAwake() {
    if (!caffeinate)
        return;
    try {
        caffeinate.kill('SIGTERM');
    }
    catch {
        /* already dead */
    }
    caffeinate = null;
}
export function isKeepAwakeActive() {
    return caffeinate != null && caffeinate.exitCode == null;
}
export function installKeepAwakeShutdown() {
    const stop = () => stopKeepAwake();
    process.once('SIGINT', stop);
    process.once('SIGTERM', stop);
    process.once('exit', stop);
}
