/**
 * Build Linux release artifacts.
 *
 * AppImage packaging uses Linux tooling (mksquashfs). Running it from
 * Windows PowerShell reaches linux-unpacked, then fails while creating
 * the AppImage. Build from Linux/WSL instead.
 */
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';

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

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');

function run(command, args) {
  const result = spawnSync(command, args, {
    stdio: 'inherit',
    shell: process.platform === 'win32',
  });

  if (result.status !== 0) {
    process.exit(result.status ?? 1);
  }
}

/** electron-builder для AppImage x64 часто даёт `x86_64` в имени — выравниваем под feed. */
function normalizeLinuxReleaseNames() {
  const releaseDir = path.resolve('release');
  if (!fs.existsSync(releaseDir)) return;

  for (const name of fs.readdirSync(releaseDir)) {
    if (!name.includes('x86_64')) continue;
    const from = path.join(releaseDir, name);
    const toName = name.replaceAll('x86_64', 'x64');
    const to = path.join(releaseDir, toName);
    if (from === to) continue;
    // Always replace stale x64 — otherwise feed points at an old AppImage.
    if (fs.existsSync(to)) {
      fs.rmSync(to, { force: true });
      console.log(`[pack:linux] removed stale ${toName}`);
    }
    fs.renameSync(from, to);
    console.log(`[pack:linux] renamed ${name} -> ${toName}`);
  }

  for (const ymlName of fs.readdirSync(releaseDir)) {
    if (!ymlName.startsWith('latest-linux') || !ymlName.endsWith('.yml')) continue;
    const ymlPath = path.join(releaseDir, ymlName);
    const text = fs.readFileSync(ymlPath, 'utf8');
    const next = text.replaceAll('x86_64', 'x64');
    if (next !== text) {
      fs.writeFileSync(ymlPath, next);
      console.log(`[pack:linux] patched ${ymlName} (x86_64 -> x64)`);
    }
  }
}

if (process.platform === 'win32') {
  console.error(
    [
      '[pack:linux] AppImage нельзя собрать напрямую из Windows PowerShell.',
      'Запустите команду внутри Linux/WSL из папки проекта:',
      '',
      '  cd /mnt/d/Work/my_projects/dnd_project/dnd_player',
      '  npm ci',
      '  npm run pack:linux',
    ].join('\n'),
  );
  process.exit(1);
}

run('npm', ['run', 'build']);
ensureReleaseNativeDeps(projectRoot, 'linux');
run('electron-builder', ['--linux']);
normalizeLinuxReleaseNames();
run('node', [path.join(projectRoot, 'scripts', 'verify-packaged-sharp.mjs')]);
