/**
 * Перед `electron-builder` на Windows: снять блокировку `release/win-unpacked/resources/app.asar`
 * (часто из‑за запущенного exe из прошлой распаковки).
 */
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import { ensureReleaseNativeDeps } from './release-native-prep.mjs';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const winUnpacked = path.join(root, 'release', 'win-unpacked');

function sleep(ms) {
  return new Promise((r) => setTimeout(r, ms));
}

function tryKillDndPlayer() {
  if (process.platform !== 'win32') return;
  try {
    execFileSync('taskkill', ['/F', '/IM', 'TTRPGPlayer.exe', '/T'], {
      stdio: 'ignore',
      windowsHide: true,
    });
  } catch {
    /* процесс не найден — нормально */
  }
}

async function tryRmWinUnpacked() {
  if (!fs.existsSync(winUnpacked)) return;
  for (let i = 0; i < 8; i += 1) {
    try {
      fs.rmSync(winUnpacked, { recursive: true, force: true });
      return;
    } catch {
      await sleep(500);
    }
  }
  console.warn(
    '[release-win-prep] Не удалось удалить release/win-unpacked. Закройте TTRPGPlayer и повторите pack.',
  );
}

tryKillDndPlayer();
await tryRmWinUnpacked();
ensureReleaseNativeDeps(root, 'win');
