/**
 * Tauri IPC wrapper — provides typed access to Rust backend commands.
 * Falls back gracefully when not running inside Tauri (browser mode).
 */

// Detect Tauri environment
export function isTauri(): boolean {
  return '__TAURI_INTERNALS__' in window
}

// Lazy-loaded invoke — only import when in Tauri environment
async function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
  if (!isTauri()) {
    throw new Error(`invoke('${cmd}') 在 Tauri 环境外被调用`)
  }
  const { invoke: tauriInvoke } = await import('@tauri-apps/api/core')
  return tauriInvoke<T>(cmd, args)
}

/** Start the Python backend sidecar. Returns the port it bound to. */
export async function startBackend(): Promise<number> {
  return invoke<number>('start_backend')
}

/** Get the currently bound backend port. Throws if backend not started. */
export async function getBackendPort(): Promise<number> {
  return invoke<number>('get_backend_port')
}

/** Stop the Python backend sidecar. */
export async function stopBackend(): Promise<void> {
  return invoke<void>('stop_backend')
}

/** Check if the backend is healthy (responds to /api/v1/health). */
export async function checkBackendHealth(): Promise<boolean> {
  return invoke<boolean>('check_backend_health')
}

/** Listen for a Tauri event. Returns an unlisten function. */
export async function listen<T>(event: string, handler: (payload: T) => void): Promise<() => void> {
  if (!isTauri()) {
    return () => {}
  }
  const { listen: tauriListen } = await import('@tauri-apps/api/event')
  const unlisten = await tauriListen<T>(event, (e) => handler(e.payload))
  return unlisten
}
