// Cross-platform audio/video file picker that returns an AudioFileInput the
// decoder understands: an ArrayBuffer on web, a file uri on native.
import * as DocumentPicker from 'expo-document-picker';
import { Platform } from 'react-native';

import type { AudioFileInput } from '@/lib/audio';

export type PickedAudio = AudioFileInput & { name: string };

export async function pickAudio(): Promise<PickedAudio | null> {
  const res = await DocumentPicker.getDocumentAsync({
    type: ['audio/*', 'video/*'],
    copyToCacheDirectory: true,
    multiple: false,
  });
  if (res.canceled || res.assets.length === 0) return null;

  const asset = res.assets[0]!;
  const name = asset.name || 'recording';

  if (Platform.OS === 'web') {
    // On web the uri is a blob: URL — read it into an ArrayBuffer for WebAudio.
    const data = await (await fetch(asset.uri)).arrayBuffer();
    return { data, name };
  }
  return { uri: asset.uri, name };
}
