import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';

export function archiveWindowsDirectory(directory, destination) {
  if (fs.existsSync(destination)) throw new Error('Archive output already exists; preserve the original candidate.');
  const quote = value => "'" + value.replaceAll("'", "''") + "'";
  // Windows PowerShell runs on .NET Framework. Namespace both paths so deeply
  // nested source/evidence files do not fall back to the legacy MAX_PATH limit.
  const command = "$ErrorActionPreference='Stop'; Add-Type -AssemblyName System.IO.Compression.FileSystem; [IO.Compression.ZipFile]::CreateFromDirectory("
    + quote(path.toNamespacedPath(path.resolve(directory))) + ', ' + quote(path.toNamespacedPath(path.resolve(destination)))
    + ', [IO.Compression.CompressionLevel]::Optimal, $true)';
  execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { windowsHide: true, stdio: 'pipe' });
}
