/**
 * Global npm update lock — prevents multiple 4r instances from each opening an updater window.
 */
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
export const DEFERRED_NPM_INSTALL_LOCK = '4runr-os-gnpm-in-progress.lock';
/** Lock older than this is treated as stale (crashed updater). */
const LOCK_STALE_MS = 15 * 60 * 1000;
export function globalDeferredNpmLockPath() {
    return path.join(os.tmpdir(), DEFERRED_NPM_INSTALL_LOCK);
}
function readLock() {
    const p = globalDeferredNpmLockPath();
    try {
        if (!fs.existsSync(p))
            return null;
        const raw = fs.readFileSync(p, 'utf-8').trim();
        const data = JSON.parse(raw);
        if (typeof data.startedAt !== 'number')
            return null;
        return data;
    }
    catch {
        return null;
    }
}
function isProcessRunning(pid) {
    if (!pid || pid <= 0)
        return false;
    try {
        process.kill(pid, 0);
        return true;
    }
    catch {
        return false;
    }
}
/** True when another updater window / autoUpdate is in progress. */
export function isGlobalUpdateLockActive() {
    const data = readLock();
    if (!data)
        return false;
    if (Date.now() - data.startedAt > LOCK_STALE_MS) {
        forceClearGlobalDeferredNpmLock();
        return false;
    }
    if (data.pid === process.pid)
        return true;
    if (isProcessRunning(data.pid))
        return true;
    forceClearGlobalDeferredNpmLock();
    return false;
}
/** Always remove lock (called at `4r` boot after stale check). */
export function forceClearGlobalDeferredNpmLock() {
    const p = globalDeferredNpmLockPath();
    try {
        if (fs.existsSync(p))
            fs.unlinkSync(p);
    }
    catch {
        /* ignore */
    }
}
/** Acquire lock for this process. Returns false if another live update is running. */
export function tryAcquireGlobalUpdateLock() {
    if (isGlobalUpdateLockActive()) {
        const existing = readLock();
        if (existing?.pid === process.pid)
            return true;
        return false;
    }
    const p = globalDeferredNpmLockPath();
    try {
        fs.writeFileSync(p, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), 'utf-8');
        return true;
    }
    catch {
        return false;
    }
}
export function releaseGlobalUpdateLock() {
    const data = readLock();
    if (data && data.pid !== process.pid)
        return;
    forceClearGlobalDeferredNpmLock();
}
//# sourceMappingURL=deferred-npm-install-lock.js.map