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

const repoRoot = process.cwd();
const binariesDir = path.join(repoRoot, 'src-tauri', 'binaries');

// No rename needed; ensure the sidecar exists.
const existing = 'radiocast-sidecar-x86_64-pc-windows-msvc.exe';
const expected = existing;

const src = path.join(binariesDir, existing);
const dst = path.join(binariesDir, expected);

// On Windows the running sidecar process can lock the binary and prevent rebuilds.
// Try to kill any leftover sidecar processes before proceeding. This is best-effort
// and will silently continue if no process is found or the kill fails.
function tryKillSidecar() {
  if (process.platform !== 'win32') return;
  const candidates = ['radiocast-sidecar.exe', 'radiocast-sidecar-x86_64-pc-windows-msvc.exe', 'radiocast-sidecar'];
  for (const name of candidates) {
    try {
      execSync(`taskkill /IM ${name} /F`, { stdio: 'ignore' });
      console.log(`Killed leftover sidecar process: ${name}`);
    } catch (e) {
      // ignore errors; likely means the process wasn't running
    }
  }
}

try {
  tryKillSidecar();

  if (!fs.existsSync(binariesDir)) {
    console.warn('binaries directory not found, skipping copy');
    process.exit(0);
  }

  if (!fs.existsSync(src)) {
    console.warn(`Source binary not found: ${src}. Skipping copy.`);
    process.exit(0);
  }

  console.log(`Sidecar binary present: ${dst}`);
} catch (e) {
  console.error('Failed to prepare binary:', e);
  process.exit(1);
}
