#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const ROOT = path.resolve(__dirname, '..');
const TEMP_DIR = path.join(ROOT, '.temp');
const PID_FILES = [
  path.join(TEMP_DIR, 'power.pid')
];

function readPid(filePath) {
  try {
    const pid = Number(fs.readFileSync(filePath, 'utf8').trim());
    return Number.isFinite(pid) && pid > 0 ? pid : 0;
  } catch { return 0; }
}

function removePid(filePath) {
  try { fs.rmSync(filePath, { force: true }); } catch {}
}

function stopPid(pid) {
  if (!pid || pid === process.pid) return;
  try {
    process.kill(pid, 'SIGINT');
    console.log(`power off requested: ${pid}`);
  } catch (err) {
    if (process.platform === 'win32') {
      try {
        execSync(`taskkill /PID ${pid} /T /F`, { stdio: 'ignore' });
        console.log(`power off forced: ${pid}`);
      } catch {}
    }
  }
}

const pids = PID_FILES.map(readPid).filter(Boolean);
if (!pids.length) console.log('Nodarama Verbatim is not reporting a power PID.');
pids.forEach(stopPid);
PID_FILES.forEach(removePid);
