import api from './api';

const aiService = {
    getStatus: async () => {
        const response = await api.get('/ai/status');
        return response.data.data;
    },

    chat: async (messages, userMode = false) => {
        const response = await api.post('/ai/chat', { messages, userMode });
        return response.data.data.reply;
    },

    getKnowledgeBase: async () => {
        const response = await api.get('/ai/knowledge-base');
        return response.data.data;
    },

    addKnowledgeEntry: async (data) => {
        const response = await api.post('/ai/knowledge-base', data);
        return response.data.data;
    },

    importTextToKb: async (text) => {
        const response = await api.post('/ai/knowledge-base/import-text', { text });
        return response.data.data;
    },

    importUrlToKb: async (url) => {
        const response = await api.post('/ai/knowledge-base/import-url', { url });
        return response.data.data;
    },

    importCrawlToKb: async (url, maxPages) => {
        const response = await api.post('/ai/knowledge-base/import-crawl', { url, maxPages }, { timeout: 300000 });
        return response.data.data;
    },

    importFileToKb: async (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = async () => {
                try {
                    const response = await api.post('/ai/knowledge-base/import-text', {
                        file: reader.result,
                        filename: file.name,
                    });
                    resolve(response.data.data);
                } catch (err) { reject(err); }
            };
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    },

    uploadKbImage: async (id, file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = async () => {
                try {
                    const response = await api.post(`/ai/knowledge-base/${id}/images`, {
                        image: reader.result,
                        filename: file.name,
                    });
                    resolve(response.data.data);
                } catch (err) { reject(err); }
            };
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    },

    deleteKbImage: async (id, filename) => {
        const response = await api.delete(`/ai/knowledge-base/${id}/images/${encodeURIComponent(filename)}`);
        return response.data;
    },

    updateKnowledgeEntry: async (id, data) => {
        const response = await api.put(`/ai/knowledge-base/${id}`, data);
        return response.data.data;
    },

    deleteKnowledgeEntry: async (id) => {
        const response = await api.delete(`/ai/knowledge-base/${id}`);
        return response.data;
    },
};

export default aiService;
