export function generateSafeFilename(name: string): string {
  return name
    .replace(/[<>:"/\\|?*]/g, '_')
    .replace(/\s+/g, '_')
    .replace(/\.+$/g, '')
    .slice(0, 255);
}

export function getSafeAppName(name: string): string {
  return generateSafeFilename(name).toLowerCase();
}

export function generateLinuxPackageName(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .replace(/-+/g, '-');
}

export function generateIdentifierSafeName(name: string): string {
  const cleaned = name.replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '').toLowerCase();

  if (cleaned === '') {
    const fallback = Array.from(name)
      .map((char) => {
        const code = char.charCodeAt(0);
        if (
          (code >= 48 && code <= 57) ||
          (code >= 65 && code <= 90) ||
          (code >= 97 && code <= 122)
        ) {
          return char.toLowerCase();
        }
        return code.toString(16);
      })
      .join('')
      .slice(0, 50);

    return fallback || 'pake-app';
  }

  return cleaned;
}

export function generateWindowsFilename(name: string): string {
  return name
    .replace(/[<>:"/\\|?*]/g, '_')
    .replace(/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i, '$&_')
    .slice(0, 255);
}

export function generateMacOSFilename(name: string): string {
  return name.replace(/[:]/g, '_').slice(0, 255);
}
