const WINDOWS_SUFFIXES = ['.exe', '.msi'];
const WINDOWS_HINTS = ['win', 'windows'];
const MAC_SUFFIXES = ['.dmg', '.pkg'];
const MAC_HINTS = [
  'mac',
  'macos',
  'osx',
  'darwin'
];
const LINUX_SUFFIXES = [
  '.appimage',
  '.deb',
  '.rpm'
];
const LINUX_HINTS = [
  'linux',
  'appimage',
  '.deb',
  '.rpm'
];
const ARCHIVE_SUFFIXES = [
  '.zip',
  '.tar',
  '.tar.gz',
  '.tgz',
  '.tar.xz',
  '.7z',
  '.rar'
];
const ARCHIVE_HINTS = [
  'archive',
  '.zip',
  '.tar',
  '.7z',
  '.rar'
];

function getSizedIconPath(folder: string, size: number): string {
  return `/images/${folder}/${size}x${size}.png`;
}

function includesAny(value: string, hints: string[]): boolean {
  const tokens = value.split(/[^a-z0-9]+/).filter(Boolean);

  return hints.some((hint) => tokens.includes(hint));
}

function matchesIconPattern(value: string, suffixes: string[], hints: string[] = []): boolean {
  return suffixes.some((suffix) => value.endsWith(suffix)) || includesAny(value, hints);
}

export function getOsIconPath(nameOrOs: string, size = 64): string {
  const normalized = nameOrOs.trim().toLowerCase();

  if (matchesIconPattern(normalized, WINDOWS_SUFFIXES, WINDOWS_HINTS))
    return getSizedIconPath('windows', size);

  if (matchesIconPattern(normalized, MAC_SUFFIXES, MAC_HINTS))
    return getSizedIconPath('macos', size);

  if (matchesIconPattern(normalized, LINUX_SUFFIXES, LINUX_HINTS))
    return getSizedIconPath('linux', size);

  if (matchesIconPattern(normalized, ARCHIVE_SUFFIXES, ARCHIVE_HINTS))
    return '/images/misc/zip.png';

  return '/images/misc/file.png';
}
