// Data-import DOMAIN — nnU-Net Items List adapter. Pure.
//
// Converges the feature's authoritative Items List parser/validator (itemsList/parse.ts) with the
// nnU-Net source-file synthesis (core.fromRedBrickItemsList). We do NOT re-parse JSON or re-validate
// bucket paths here — parseItemsList already owns that (IL3 NIfTI single-string, IL5 unique name,
// C2/IL6 bucket-relative). We only chain its clean tasks into nnU-Net SourceFiles that carry a
// consecutive channelIndex per series (nnU-Net: Task=Case, series=Channel).

import type { DataType } from '../dataTypes';
import type { ImportError } from '../types';
import { parseItemsList } from '../itemsList/parse';
import { fromRedBrickItemsList, type FileEnding, type SourceFile, type Split } from './core';

export interface NnunetItemsListResult {
  /** Synthesized nnU-Net source files (one per series, channelIndex by series order). Empty if !ok. */
  files: SourceFile[];
  /** Parse/validation errors from the shared Items List parser (located for per-row display). */
  errors: ImportError[];
  /** True iff the Items List parsed and every entry validated cleanly. */
  ok: boolean;
}

/**
 * Parse + validate an Items List JSON (via the shared parser), then convert each clean task into
 * nnU-Net source files. Only converts when the parse is clean, so malformed input surfaces errors
 * without producing half-mapped files. `ItemsListTask` is structurally a `RedBrickEntry`.
 */
export function nnunetSourceFilesFromItemsList(
  json: string,
  dataType: DataType,
  ending: FileEnding,
  split: Split = 'train',
): NnunetItemsListResult {
  const parsed = parseItemsList(json, dataType);
  const files = parsed.ok ? fromRedBrickItemsList(parsed.tasks, ending, split) : [];
  return { files, errors: parsed.errors, ok: parsed.ok };
}
