import { invoke } from "$lib/runtime/invoke";
import {
  startRecording as startMicRecording,
  stopRecording as stopMicRecording,
} from "tauri-plugin-mic-recorder-api";

type SpeechControlResult = {
  running: boolean;
  pid?: number;
  launch?: string;
};

export async function startSpeechDictation(): Promise<SpeechControlResult> {
  return invoke<SpeechControlResult>("speech_start");
}

export async function stopSpeechDictation(): Promise<SpeechControlResult> {
  return invoke<SpeechControlResult>("speech_stop");
}

export async function probeMicrophoneAccess(): Promise<string> {
  await startMicRecording();
  await new Promise((resolve) => setTimeout(resolve, 300));
  const outputPath = await stopMicRecording();
  try {
    await invoke<{ deleted: boolean }>("speech_cleanup_probe", {
      path: outputPath,
    });
  } catch {
    // Keep probe non-blocking; cleanup failure should not break dictation start.
  }
  return outputPath;
}
