// ✅ Capture 20-sec chunks & send to Deepgram
function processAudioChunk() {
  console.log("🎙 Capturing 20-sec audio chunk...");

  const uniqueFileName = `${Date.now()}_temp_audio.wav`;  // Create unique file name
  const tempFilePath = path.join(TEMP_DIR, uniqueFileName);

  // Build the ffmpeg command using the provided RTMP URL
  const ffmpegCommand = `${FFMPEG_PATH} -y -rtmp_live live -i "${providedRtmpUrl}" -t ${CHUNK_DURATION} -acodec pcm_s16le -ac 1 -ar 16000 "${tempFilePath}"`;

  console.log("Executing ffmpeg command:", ffmpegCommand);

  exec(ffmpegCommand, async (error, stdout, stderr) => {
    if (error) {
      console.error("❌ Error capturing audio chunk:", error);
      console.error("ffmpeg stderr:", stderr);
      return;
    }
    console.log("✅ Audio chunk saved. Sending to Deepgram...");

    // Send audio to Deepgram
    const transcript = await transcribeWithDeepgram(tempFilePath);
    if (transcript) {
      console.log("✅ Transcription Received:", transcript);
      await saveToDatabase(transcript);
      fs.unlinkSync(tempFilePath);
    }
    // Manage file count: delete oldest files if needed
    manageFiles();
  });
}

// ✅ Send Audio to Deepgram
async function transcribeWithDeepgram(audioFile) {
  try {
    const audioData = fs.createReadStream(audioFile);
    const response = await axios.post(
      "https://api.deepgram.com/v1/listen",
      audioData,
      {
        headers: {
          Authorization: `Token ${DEEPGRAM_API_KEY}`,
          "Content-Type": "audio/wav"
        },
        params: {
          model: "nova",
          language: "en",
          smart_format: true,
          detect_language: true
        }
      }
    );
    if (response.data && response.data.results) {
      return response.data.results.channels[0].alternatives[0].transcript;
    }
    console.error("❌ Deepgram response error: No results found.");
    return null;
  } catch (error) {
    console.error("❌ Deepgram API Error:", error.response?.data || error.message);
    return null;
  }
}