// Typed bridge to the Rust backend (concat-only build).

import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { open } from "@tauri-apps/plugin-dialog";
import { revealItemInDir } from "@tauri-apps/plugin-opener";

export interface Tools { ffmpeg: string | null; ffprobe: string | null; }
export interface DurationInfo { path: string; duration: number; }
export interface ConcatResult { output: string; size_mb: number; elapsed: number; }
export interface ConcatProgress { pct: number; status: string; elapsed: number; eta: number; speed: number; }

export const getTools = () => invoke<Tools>("get_tools");
export const probeDurations = (paths: string[]) => invoke<DurationInfo[]>("probe_durations", { paths });
export const isVideo = (path: string) => invoke<boolean>("is_video", { path });
export const startConcat = (files: string[], output: string) =>
  invoke<ConcatResult>("start_concat", { files, output });
export const cancel = () => invoke<void>("cancel");
export const deleteFiles = (paths: string[]) => invoke<number>("delete_files", { paths });
export const bililiveRename = (stem: string) => invoke<string | null>("bililive_rename", { stem });

export const onConcatProgress = (cb: (p: ConcatProgress) => void): Promise<UnlistenFn> =>
  listen<ConcatProgress>("concat-progress", (e) => cb(e.payload));

export const onFilesDropped = (cb: (paths: string[]) => void): Promise<UnlistenFn> =>
  getCurrentWebview().onDragDropEvent((e) => {
    if (e.payload.type === "drop") cb(e.payload.paths);
  });

export async function pickVideos(): Promise<string[]> {
  const sel = await open({
    multiple: true,
    filters: [{ name: "Video", extensions: ["mp4", "mov", "mkv", "avi", "flv", "ts", "wmv", "m4v", "webm", "mts", "m2ts"] }],
  });
  if (!sel) return [];
  return Array.isArray(sel) ? sel : [sel];
}

export async function pickFolder(): Promise<string | null> {
  const sel = await open({ directory: true, multiple: false });
  return typeof sel === "string" ? sel : null;
}

export const reveal = (path: string) => revealItemInDir(path);
