import { StemGroupId, StemTypeId } from '@/components/edit2025/StemsContext';
import { ApiClient } from '@/lib/apiClient';

import { sleep } from './utils';

export default async function fetchClipStems(
  apiClient: ApiClient,
  clipId: string
) {
  let attempts = 0;
  const poll = async () => {
    const response = await apiClient.GET('/api/gen/{clip_id}/instruments', {
      params: {
        path: {
          clip_id: clipId,
        },
      },
    });
    if (!response.data) {
      console.error(response);
      throw new Error(`Error fetching clip stems: ${(response as any).error}`);
    }
    if (response.data.state === 'complete') {
      return response.data;
    }
    if (attempts > 10) {
      console.error('Failed to get instruments for clip', clipId);
      return [];
    }
    attempts++;
    await sleep(2500);
    return poll();
  };

  const response = await poll();
  return response as {
    state: 'complete';
    groups: (keyof typeof StemGroupId)[];
    instruments: (keyof typeof StemTypeId)[];
  };
}
