import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';
export function getDefaultSupervisorLockFilePath() {
    return join(homedir(), '.reviewflow', 'supervisor.lock');
}
export function createDefaultSupervisorLockFileSystem() {
    return {
        readFile(path) {
            if (!existsSync(path))
                return null;
            return readFileSync(path, 'utf-8');
        },
        writeFile(path, content) {
            mkdirSync(dirname(path), { recursive: true });
            writeFileSync(path, content, 'utf-8');
        },
        deleteFile(path) {
            if (existsSync(path))
                unlinkSync(path);
        },
        ensureDirectory(path) {
            mkdirSync(path, { recursive: true });
        },
        isProcessAlive(pid) {
            try {
                process.kill(pid, 0);
                return true;
            }
            catch {
                return false;
            }
        },
    };
}
function parsePid(content) {
    const trimmed = content.trim();
    if (!/^\d+$/.test(trimmed))
        return null;
    const parsed = Number.parseInt(trimmed, 10);
    return Number.isFinite(parsed) ? parsed : null;
}
export class SupervisorLockFileSystemGateway {
    deps;
    constructor(deps) {
        this.deps = deps;
    }
    async acquire() {
        const { fileSystem, lockFilePath, currentPid } = this.deps;
        const existing = fileSystem.readFile(lockFilePath);
        if (existing !== null) {
            const ownerPid = parsePid(existing);
            if (ownerPid !== null && fileSystem.isProcessAlive(ownerPid)) {
                return { acquired: false, reason: `lock held by live pid ${ownerPid}` };
            }
        }
        fileSystem.writeFile(lockFilePath, String(currentPid));
        return { acquired: true, reason: null };
    }
    async release() {
        const { fileSystem, lockFilePath, currentPid } = this.deps;
        const existing = fileSystem.readFile(lockFilePath);
        if (existing === null)
            return;
        const ownerPid = parsePid(existing);
        if (ownerPid !== currentPid)
            return;
        fileSystem.deleteFile(lockFilePath);
    }
}
//# sourceMappingURL=supervisorLock.fileSystem.gateway.js.map