import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';

export const VideoLearningService = {
    async checkDependencies(): Promise<boolean> {
        return await invoke('check_whisper_dependencies');
    },

    async checkModelExists(): Promise<boolean> {
        return await invoke('check_whisper_model_exists');
    },

    async downloadModel(
        onProgress: (current: number, total: number) => void,
        token?: string
    ): Promise<string> {
        const unlisten = await listen<{ 0: number, 1: number }>('download-whisper-progress', (event) => {
            onProgress(event.payload[0], event.payload[1]);
        });

        try {
            const result = await invoke<string>('download_whisper_model', {
                url: "https://huggingface.co/NbAiLab/nb-whisper-medium-gguf/resolve/main/nb-whisper-medium-q5_0.gguf",
                token
            });
            return result;
        } finally {
            unlisten();
        }
    },

    async transcribeVideo(videoPath: string): Promise<any> {
        const jsonStr = await invoke<string>('transcribe_media', { videoPath });
        try {
            return JSON.parse(jsonStr);
        } catch (e) {
            console.error("Failed to parse Whisper JSON", e);
            throw new Error("Invalid Whisper output format");
        }
    }
};
