// Data-import DOMAIN — Direct Upload state machine: States, Events, Context. Pure.
// Source: docs/workflows/data-import-spec.md §3 (the §3:83-93 transition table + guards D1-D6).
// The reducer (reducer.ts) is a pure transition function; side effects (upload, process) live in
// the application use-case, which dispatches the OK/FAIL/PROGRESS events back into the machine.

import type { DataType } from '../dataTypes';
import type { ImportError, StagedFile } from '../types';

export type DirectState =
  | 'SelectingType'
  | 'ConfiguringStructure'
  | 'Staging'
  | 'Validating'
  | 'Uploading'
  | 'Processing'
  | 'Complete'
  | 'UploadError'
  | 'PartialFailure';

export interface DirectContext {
  /** The one image data type for this upload (D1 — exactly one). */
  dataType: DataType | null;
  /** D2 — only ever true for DICOM/NIfTI. */
  groupByStudy: boolean;
  files: StagedFile[];
  /** Upload progress 0..100. */
  progress: number;
  errors: ImportError[];
  /** Task ids created server-side once Processing completes. */
  createdTaskIds: string[];
}

export type DirectEvent =
  | { type: 'SELECT_TYPE'; dataType: DataType }
  | { type: 'TOGGLE_GROUP_BY_STUDY' }
  | { type: 'ADD_FILES'; files: StagedFile[] }
  | { type: 'CLEAR_FILES' }
  | { type: 'START_UPLOAD' }
  | { type: 'VALIDATE_OK' }
  | { type: 'VALIDATE_FAIL'; errors: ImportError[] }
  | { type: 'UPLOAD_PROGRESS'; progress: number }
  | { type: 'UPLOAD_OK' }
  | { type: 'UPLOAD_FAIL'; errors?: ImportError[] }
  | { type: 'PROCESS_OK'; taskIds: string[] }
  | { type: 'PROCESS_FAIL'; errors?: ImportError[] }
  | { type: 'RETRY' };

export interface DirectMachine {
  state: DirectState;
  context: DirectContext;
}

export const initialDirectContext: DirectContext = {
  dataType: null,
  groupByStudy: false,
  files: [],
  progress: 0,
  errors: [],
  createdTaskIds: [],
};

export const initialDirectMachine: DirectMachine = {
  state: 'SelectingType',
  context: initialDirectContext,
};
