import { setAudioModeAsync } from 'expo-audio'

// Audio session bootstrap. Called once at boot alongside `applyVideoCacheCap()`
// so subsequent `useVideoPlayer` instances inherit a consistent audio session
// category instead of expo-video's per-platform defaults.
//
// Policy:
//   - `playsInSilentMode: true` — required for iOS background audio. The
//     hardware silent switch consequently does NOT mute feed videos. This
//     is fine because feed cells are muted-by-default; only a deliberate
//     user tap unmutes one, and that audible player overrides this with
//     `audioMixingMode: 'duckOthers'`.
//   - `shouldPlayInBackground: true` — pairs with the per-player
//     `staysActiveInBackground` toggle the audible holder will set in
//     Phase 2. With this off, locking the screen would tear down the
//     AVPlayer regardless of what the player itself requested.
//   - `interruptionMode: 'mixWithOthers'` — global default so muted
//     scrolling does not pause the user's Music/Podcasts. The audible
//     player flips its own `audioMixingMode` to `'duckOthers'` per
//     instance when it claims the audio slot.
//   - `allowsRecording: false` — recording is owned by expo-camera /
//     expo-image-picker for the composer; the playback session must not
//     downgrade to `playAndRecord`, which would route audio through the
//     earpiece on iOS.
export async function applyAudioSession(): Promise<void> {
  try {
    await setAudioModeAsync({
      playsInSilentMode: true,
      shouldPlayInBackground: true,
      interruptionMode: 'mixWithOthers',
      allowsRecording: false,
      shouldRouteThroughEarpiece: false,
    })
  } catch {
    // Best-effort: the native module is not always ready on cold start
    // (e.g. some older Android emulator images). A missed apply degrades
    // to expo-video's defaults — non-fatal.
  }
}
