#!/usr/bin/env node
import fs from 'fs';
import path from 'path';

const repoRoot = process.cwd();
const tauriDir = path.join(repoRoot, 'src-tauri');
const resourcesDir = path.join(tauriDir, 'resources');

function platformBinName() {
  return process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg';
}

function exists(p) {
  try { return fs.existsSync(p); } catch { return false; }
}

function ensureDir(p) {
  if (!exists(p)) fs.mkdirSync(p, { recursive: true });
}

// Source lookup order:
// 1) RADIOPLAYER_FFMPEG (absolute or relative)
// 2) tools/ffmpeg/ffmpeg(.exe)
// 3) tools/ffmpeg/bin/ffmpeg(.exe)
function resolveSource() {
  const env = process.env.RADIOPLAYER_FFMPEG;
  if (env && String(env).trim().length > 0) {
    const p = path.isAbsolute(env) ? env : path.join(repoRoot, env);
    if (exists(p)) return p;
    console.warn(`RADIOPLAYER_FFMPEG set but not found: ${p}`);
  }

  const name = platformBinName();
  const candidates = [
    path.join(repoRoot, 'tools', 'ffmpeg', name),
    path.join(repoRoot, 'tools', 'ffmpeg', 'bin', name),
  ];

  return candidates.find(exists) || null;
}

function main() {
  const name = platformBinName();
  // If CI or prior steps already placed ffmpeg into resources, prefer that and skip copying.
  const existingInResources = path.join(resourcesDir, name);
  if (exists(existingInResources)) {
    console.log(`FFmpeg already present in resources: ${existingInResources} — skipping copy.`);
    process.exit(0);
  }
  // Also search recursively in resources for any ffmpeg-like file (robustness for nested archives)
  if (exists(resourcesDir)) {
    const files = fs.readdirSync(resourcesDir, { withFileTypes: true });
    const found = (function findRec(dir) {
      for (const f of fs.readdirSync(dir, { withFileTypes: true })) {
        const p = path.join(dir, f.name);
        if (f.isFile() && f.name.toLowerCase().startsWith('ffmpeg')) return p;
        if (f.isDirectory()) {
          const r = findRec(p);
          if (r) return r;
        }
      }
      return null;
    })(resourcesDir);
    if (found) {
      console.log(`Found ffmpeg in resources at ${found} — skipping copy.`);
      process.exit(0);
    }
  }
  const src = resolveSource();
  if (!src) {
    console.log('FFmpeg not provided; skipping copy (set RADIOPLAYER_FFMPEG or place it under tools/ffmpeg/).');
    process.exit(0);
  }

  ensureDir(resourcesDir);
  const dst = path.join(resourcesDir, name);

  try {
    fs.copyFileSync(src, dst);
    // Best-effort: ensure executable bit on unix-like platforms.
    if (process.platform !== 'win32') {
      try { fs.chmodSync(dst, 0o755); } catch {}
    }
    console.log(`Copied FFmpeg into bundle resources: ${src} -> ${dst}`);
  } catch (e) {
    console.error('Failed to copy FFmpeg:', e);
    process.exit(1);
  }
}

main();
