#!/usr/bin/env node
import { spawnSync } from 'child_process';
import fs from 'fs';
import path from 'path';

const repoRoot = process.cwd();
const exePath = path.join(repoRoot, 'src-tauri', 'target', 'release', 'RadioPlayer.exe');
const iconPath = path.join(repoRoot, 'src-tauri', 'icons', 'icon.ico');

if (!fs.existsSync(exePath)) {
  console.warn(`RadioPlayer exe not found at ${exePath}. Skipping rcedit patch.`);
  process.exit(0);
}

if (!fs.existsSync(iconPath)) {
  console.warn(`Icon not found at ${iconPath}. Skipping rcedit patch.`);
  process.exit(0);
}

console.log('Patching EXE icon with rcedit...');

// Prefer local installed binary to avoid relying on npx.
// Note: the `rcedit` npm package places the binary at node_modules/rcedit/bin/rcedit.exe
// and does not always create a node_modules/.bin shim.
const binDir = path.join(repoRoot, 'node_modules', '.bin');
const packageBinDir = path.join(repoRoot, 'node_modules', 'rcedit', 'bin');
const localCandidates = process.platform === 'win32'
  ? [
      // Preferred: direct binary shipped by the package
      path.join(packageBinDir, 'rcedit.exe'),
      // Fallbacks: npm/yarn shim locations (if present)
      path.join(binDir, 'rcedit.cmd'),
      path.join(binDir, 'rcedit.exe'),
      path.join(binDir, 'rcedit'),
    ]
  : [path.join(binDir, 'rcedit')];

const localBin = localCandidates.find(p => fs.existsSync(p));

let cmd, args;
if (localBin) {
  cmd = localBin;
  args = [exePath, '--set-icon', iconPath];
} else {
  // Last resort fallback to npx.
  cmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
  args = ['rcedit', exePath, '--set-icon', iconPath];
}

const res = spawnSync(cmd, args, { stdio: 'inherit' });

if (res.error) {
  console.error(`Failed to run ${cmd}:`, res.error.message);
  console.error('Ensure rcedit is installed and available as a .cmd/.exe in node_modules/.bin (run `npm install`).');
  console.error('If you rely on npx, make sure you have npx.cmd on PATH (PowerShell-only shims like npx.ps1 will not work with Node spawn).');
  process.exit(1);
}

if (res.status !== 0) {
  console.error(`rcedit exited with code ${res.status}`);
  process.exit(res.status);
}

console.log('Icon patched successfully.');
