import type { SoundRecipe, SoundRecipeWaveform } from '@/shared/types/audioFiles';

/**
 * Local stub for AI sound generation. Until an AI key is wired, this produces a
 * pleasant pseudo-random synthesis recipe entirely client-side — a real,
 * audible "generated" sound with no AI call. The rest of the pipeline (persist
 * to `audio_files` as a `recipe` row, play via {@link playRecipe}, list in the
 * library) is identical to the eventual AI path: only this function's body
 * changes when the key lands (local recipe → AI-produced recipe from a prompt).
 */

// Pentatonic scale — any subset sounds consonant, which keeps random output
// gentle (the timer is used with sound-sensitive students).
const PENTATONIC_SCALE = [523.25, 587.33, 659.25, 783.99, 880, 1046.5];
const WAVEFORMS: readonly SoundRecipeWaveform[] = ['sine', 'triangle'];
const GENERATED_NAME_PARTS = [
  'Aurora',
  'Meadow',
  'Tide',
  'Lantern',
  'Willow',
  'Cinder',
  'Pebble',
  'Drift',
];

function pick<T>(values: readonly T[]): T {
  return values[Math.floor(Math.random() * values.length)];
}

export function generateSoundRecipe(): SoundRecipe {
  const noteCount = 3 + Math.floor(Math.random() * 3); // 3–5 notes
  const waveform = pick(WAVEFORMS);
  const ascending = Math.random() < 0.5;

  const notes = Array.from({ length: noteCount }, (_, index) => {
    const scaleIndex = ascending ? index : noteCount - 1 - index;
    return {
      freq: PENTATONIC_SCALE[scaleIndex % PENTATONIC_SCALE.length],
      startAt: index * 0.18,
      duration: 0.7,
      gain: 0.3,
      attack: 0.02,
    };
  });

  return { voices: [{ waveform, notes }] };
}

export function generateSoundTitle(): string {
  return `${pick(GENERATED_NAME_PARTS)} ${pick(GENERATED_NAME_PARTS)}`;
}
