/**
 * Light, VTK-free helpers for the ImageHub dataset viewer.
 *
 * These deliberately live in the MAIN @ump/shared barrel (not in the heavy
 * `@ump/shared/viewer` entry) so a page can decide *whether* a file is viewable
 * and fetch it as a `File` without pulling in @kitware/vtk.js. The actual
 * renderer is lazy-loaded separately so VTK only loads when a viewer opens.
 */

/** Imaging file extensions the bundled viewer can render (DICOM + NIfTI). */
export const VIEWABLE_IMAGING_EXTENSIONS = ['.nii.gz', '.nii', '.dcm', '.dicom'] as const;

/** True when a logical path / filename looks like a viewer-renderable imaging file. */
export function isViewableImagingFile(name: string): boolean {
  const n = (name || '').toLowerCase();
  return VIEWABLE_IMAGING_EXTENSIONS.some((ext) => n.endsWith(ext));
}

/**
 * Coarse format routing for a filename — mirrors the viewer's own extension
 * detection. `.nii`/`.nii.gz` → nifti, `.dcm`/`.dicom` → dicom, else null.
 */
export function imagingFormatOf(name: string): 'dicom' | 'nifti' | null {
  const n = (name || '').toLowerCase();
  if (n.endsWith('.nii') || n.endsWith('.nii.gz')) return 'nifti';
  if (n.endsWith('.dcm') || n.endsWith('.dicom')) return 'dicom';
  return null;
}

/**
 * Download a (presigned) URL and wrap the bytes in a `File` the viewer accepts.
 * The viewer auto-detects DICOM vs NIfTI from the file name, so the original
 * logical path must be preserved as the File name.
 */
export async function fetchAsFile(url: string, name: string, type?: string): Promise<File> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Tải tệp thất bại (HTTP ${res.status})`);
  const blob = await res.blob();
  return new File([blob], name, { type: type || blob.type || 'application/octet-stream' });
}
