// Data-import DOMAIN — D6: an `.mhd` upload is invalid unless its companion raw data file
// (`.raw`/`.img` uncompressed, or `.zraw` compressed) with the same base name is in the same
// folder. Pure. Source: docs/workflows/data-import-spec.md §3 (D6) + §2.1.

import { extensionOf, MHD_COMPANION_EXTENSIONS } from '../formats';
import { importError, type ImportError, type StagedFile } from '../types';
import { dirOf, stripExtension } from './paths';

/** Composite key locating a logical volume within its folder: `<dir>::<baseName>`. */
function volumeKey(file: StagedFile): string {
  return `${dirOf(file.relativePath)}::${stripExtension(file.name)}`;
}

/**
 * Return one MHD_COMPANION_MISSING error per `.mhd` file that lacks a sibling raw companion.
 * Empty array = all companions present (or no `.mhd` files at all).
 */
export function validateMhdCompanions(files: readonly StagedFile[]): ImportError[] {
  // Index every present raw-companion file by its <dir>::<base> key.
  const companions = new Set<string>();
  for (const f of files) {
    if ((MHD_COMPANION_EXTENSIONS as readonly string[]).includes(extensionOf(f.name))) {
      companions.add(volumeKey(f));
    }
  }

  const errors: ImportError[] = [];
  for (const f of files) {
    if (extensionOf(f.name) !== '.mhd') continue;
    if (!companions.has(volumeKey(f))) {
      errors.push(
        importError(
          'MHD_COMPANION_MISSING',
          `Tệp "${f.name}" thiếu tệp dữ liệu đi kèm (.raw/.img/.zraw) cùng tên trong cùng thư mục.`,
          { file: f.relativePath },
        ),
      );
    }
  }
  return errors;
}
