import { isObject, isString, makeFixer } from './utils';

export type InstrumentSpec =
  | {
      type: 'song';
    }
  | {
      type: 'custom';
      prompt: string;
    }
  | {
      type: 'nonVocalPreset';
      prompt: string;
    }
  | {
      type: 'vocalPreset';
      prompt: string;
    };

export const DEFAULT_INSTRUMENT: InstrumentSpec = {
  type: 'song',
};

export const fixPrompt = makeFixer(isString, '');

export default function fixInstrumentSpec(
  instrumentSpec: unknown
): InstrumentSpec {
  if (!isObject(instrumentSpec)) {
    return DEFAULT_INSTRUMENT;
  }

  const i = instrumentSpec as { type: unknown };

  if (i.type === 'song') {
    return { type: 'song' };
  }

  if (i.type === 'custom') {
    const custom = instrumentSpec as { type: 'custom'; prompt: unknown };
    custom.prompt = fixPrompt(custom.prompt);
    return instrumentSpec as InstrumentSpec;
  }

  if (i.type === 'nonVocalPreset') {
    const preset = instrumentSpec as {
      type: 'nonVocalPreset';
      prompt: unknown;
    };
    preset.prompt = fixPrompt(preset.prompt);
    return instrumentSpec as InstrumentSpec;
  }

  if (i.type === 'vocalPreset') {
    const preset = instrumentSpec as { type: 'vocalPreset'; prompt: unknown };
    preset.prompt = fixPrompt(preset.prompt);
    return instrumentSpec as InstrumentSpec;
  }

  // Default to song type
  return DEFAULT_INSTRUMENT;
}
