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

export interface AIModelStatus {
    exists: boolean;
    serverRunning: boolean;
    downloadProgress?: number;
    downloadTotal?: number;
}

const SERVER_URL = "http://localhost:8080/v1/chat/completions";

export const LocalAIService = {
    async checkModelExists(): Promise<boolean> {
        return invoke<boolean>("check_model_exists");
    },

    async downloadModel(url: string, token?: string, onProgress?: (current: number, total: number) => void): Promise<string> {
        if (onProgress) {
            await listen<[number, number]>("download-progress", (event) => {
                onProgress(event.payload[0], event.payload[1]);
            });
        }
        return invoke<string>("download_model", { url, token });
    },

    async checkVisionModelExists(): Promise<boolean> {
        return invoke<boolean>("check_vision_model_exists");
    },

    async downloadVisionModel(url: string, projUrl?: string, token?: string, onProgress?: (current: number, total: number) => void): Promise<string> {
        if (onProgress) {
            await listen<[number, number]>("download-vision-progress", (event) => {
                onProgress(event.payload[0], event.payload[1]);
            });
        }
        return invoke<string>("download_vision_model", { url, projUrl, token });
    },

    async analyzeImage(imagePath: string): Promise<string> {
        return invoke<string>("analyze_image", { imagePath });
    },

    async startServer(): Promise<string> {
        return invoke<string>("start_chat");
    },

    async chatCompletion(messages: { role: string; content: string }[]): Promise<string> {
        try {
            const response = await fetch(SERVER_URL, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    messages,
                    stream: false, // For now handle non-streaming
                    n_predict: 512, // Default max tokens
                    temperature: 0.7,
                }),
            });

            if (!response.ok) {
                throw new Error(`AI Server error: ${response.statusText}`);
            }

            const data = await response.json();
            return data.choices[0].message.content;
        } catch (error) {
            console.error("Failed to fetch from AI server", error);
            throw error;
        }
    }
};
