import * as fs from 'node:fs';

export function acquireRuntimeLock(lockPath: string) {
  const data = JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() });
  try {
    fs.writeFileSync(lockPath, data, { flag: 'wx' });
    return;
  } catch (e: any) {
    if (e.code !== 'EEXIST') throw e;
  }
  // Lock file exists — check if the process is still alive
  const current = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as { pid: number };
  try {
    process.kill(current.pid, 0);
    throw new Error(`GPU Guard 已在运行，PID=${current.pid}`);
  } catch (e: any) {
    if (e.message?.includes('GPU Guard 已在运行')) throw e;
    // Stale lock — remove and retry
    fs.rmSync(lockPath, { force: true });
    fs.writeFileSync(lockPath, data, 'utf8');
  }
}

export function readRuntimeLock(lockPath: string): { pid: number; startedAt: string } {
  return JSON.parse(fs.readFileSync(lockPath, 'utf8'));
}

export function releaseRuntimeLock(lockPath: string) {
  fs.rmSync(lockPath, { force: true });
}
