#!/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 (node_modules/.bin/rcedit) to avoid relying on npx in some CI/envs
const localBin = path.join(repoRoot, 'node_modules', '.bin', process.platform === 'win32' ? 'rcedit.exe' : 'rcedit');
let cmd, args;
if (fs.existsSync(localBin)) {
  cmd = localBin;
  args = [exePath, '--set-icon', iconPath];
} else {
  // fallback to 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 (npm install --save-dev rcedit) or that npx is available.');
  process.exit(1);
}

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

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