const vscode = require('vscode');
const axios = require('axios');
const FileDataProvider = require('./fileDataProvider');
const { getWebviewContent } = require('./webviewPanel');

const selectedFiles = FileDataProvider.selectedFiles;
const fileDataProvider = new FileDataProvider.FileDataProvider();

async function handleQuestionSubmission(panel, question, selectedUris) {
    // Update the selectedFiles array based on the selectedUris
    selectedFiles.forEach(file => {
        file.selected = selectedUris.includes(file.uri.fsPath);
    });

    fileDataProvider.refresh();

    const fileContents = selectedFiles
        .filter(file => file.selected)
        .map(file => {
            const document = vscode.workspace.textDocuments.find(doc => doc.uri.fsPath === file.uri.fsPath);
            if (document) {
                const lines = document.getText().split('\n');
                const formattedLines = lines.map(line => `\t${line}`).join('\n');
                return `${file.uri.fsPath}:\n\`\`\`\n${formattedLines}\n\`\`\``;
            }
            return '';
        })
        .join('\n\n');

    // Call Llama3 API with the question and file contents
    try {
        const response = await axios.post('http://127.0.0.1:11434/api/chat', {
            model: "llama3",
            messages: [
                { role: "user", content: question + "\n" + fileContents},
            ],
        });

        // Extract the answer from the Llama3 response
        const answer = response.data.choices[0].message.content;

        // Update the webview content to display only the Llama3 response
        panel.webview.html = getWebviewContent(answer, question);
    } catch (error) {
        // Handle any errors from the Llama3 API
        console.error("Failed to get Llama3 response:", error);
        panel.webview.html = getWebviewContent(`Failed to get response from Llama3 API. Error: ${error.message}`, question);
    }
}

module.exports = {
    handleQuestionSubmission,
    fileDataProvider,
    selectedFiles
};