// AGPL-3.0-only
//
// This is free software for the public good of a permacomputer
// hosted at permacomputer.com, an always-on computer by the people, for the
// people. One which is durable, easy to repair, and distributed like tap water
// for machine learning intelligence.
//
// The permacomputer is community-owned infrastructure optimized around
// four values:
//
//   TRUTH    - First principles, math & science, open source code
//   FREEDOM  - Voluntary partnerships, freedom from tyranny & corporate control
//   HARMONY  - Minimal waste, self-renewing systems with diverse connections
//   LOVE     - Be yourself without hurting others, cooperation through natural law
//
// This software contributes to that vision by making machine learning
// accessible to everyone through a free, open, embeddable chat interface.
// Code is seeds to sprout on any abandoned technology.
//
// Learn more: https://www.permacomputer.com
//
// NO WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
//
// Copyright 2025-2026 TimeHexOn & foxhop & russell@unturf
// https://www.permacomputer.com

import { chatHistory } from "./chat.js";
import { MEGAPARCE_API_URL } from "./config.js";
import { speakText } from "./tts.js";

// Progress indicator functions
export function showProgressIndicator(message) {
	// Remove existing indicator if any
	hideProgressIndicator();

	const indicator = document.createElement("div");
	indicator.id = "progress-indicator";
	indicator.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 20px;
    border-radius: 5px;
    z-index: 9999;
  `;
	indicator.textContent = message || "Processing...";
	document.body.appendChild(indicator);
}

export function hideProgressIndicator() {
	const indicator = document.getElementById("progress-indicator");
	if (indicator) {
		indicator.remove();
	}
}

// Handle file upload from input element
export async function handleFileUpload() {
	const fileInput = document.getElementById("file-input");
	if (!fileInput.files[0]) {
		alert(getUIText("pleaseSelectFile"));
		return;
	}

	try {
		showProgressIndicator("Uploading file...");
		const response = await uploadFile(fileInput.files[0]);
		hideProgressIndicator();

		await integrateMegafarceResponse(response);
		fileInput.value = ""; // Clear the input after upload
	} catch (error) {
		console.error("File upload error:", error);
		hideProgressIndicator();
	}
}

// Upload File to MegaFarce with Progress Indicator
export async function uploadFile(file) {
	const formData = new FormData();
	formData.append("file", file);

	const response = await fetch(MEGAPARCE_API_URL, {
		method: "POST",
		body: formData,
	});

	if (!response.ok) {
		const errorText = await response.text();
		throw new Error(`Error uploading file: ${errorText}`);
	}

	const responseData = await response.json();
	return responseData;
}

// Integrate MegaFarce Response into Chat
export async function integrateMegafarceResponse(response) {
	// Assuming the response contains a 'content' field with the parsed content
	const content = response.content || response.result || "No content received.";

	// Add a system message with the uploaded content to provide context
	chatHistory.push({ role: "system", content: `Uploaded Context: ${content}` });

	// Note: System message is added to chat history for context but not displayed to user
	// The uploaded content context is available to the AI without showing it in the chat

	// Add Generate TTS button for the uploaded content
	const generateTTSButton = document.createElement("button");
	generateTTSButton.textContent = "Generate TTS for Uploaded Content";
	let ttsAudio = null;
	let ttsBlob = null;
	let isPaused = false;

	generateTTSButton.onclick = async () => {
		if (!ttsAudio) {
			generateTTSButton.textContent = "Processing...";
			generateTTSButton.disabled = true; // Disable button while processing
			try {
				const result = await speakText(content);
				ttsAudio = result.audio;
				ttsBlob = result.blob;
				generateTTSButton.textContent = "Pause TTS";
				generateTTSButton.disabled = false; // Re-enable button after processing
				ttsAudio.play();

				// Add download button for the TTS audio
				const downloadButton = document.createElement("button");
				downloadButton.textContent = "Download MP3";
				downloadButton.onclick = () => {
					const a = document.createElement("a");
					a.href = URL.createObjectURL(ttsBlob);
					a.download = "uploaded-content.mp3";
					a.click();
				};
				chatBox.appendChild(downloadButton);
			} catch (error) {
				console.error("Error generating TTS:", error);
				generateTTSButton.textContent = "Generate TTS for Uploaded Content";
				generateTTSButton.disabled = false;
			}
		} else {
			if (isPaused) {
				ttsAudio.play();
				generateTTSButton.textContent = "Pause TTS";
			} else {
				ttsAudio.pause();
				generateTTSButton.textContent = "Play TTS";
			}
			isPaused = !isPaused;
		}
	};
	chatBox.appendChild(generateTTSButton);
}

// Add file upload button
export function addFileUploadButton() {
	const button = document.createElement("button");
	button.textContent = "Upload File";
	button.className = "uncloseai-ui-button-margin";

	const fileInput = document.createElement("input");
	fileInput.type = "file";
	fileInput.id = "file-input";
	fileInput.style.display = "none"; // Hidden input must remain inline

	button.onclick = () => fileInput.click();
	fileInput.onchange = handleFileUpload;

	document.body.appendChild(button);
	document.body.appendChild(fileInput);
}
