const db = require("../config/db");
const axios = require("axios");
const fs = require("fs");
const {exec} = require("child_process")

require("dotenv").config();


const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const DEEPGRAM_API_KEY = process.env.DEEPGRAM_API_KEY;



// ✅ API Endpoint: Process Live Transcription
// ✅ Process Live RTMP Stream for Transcription
exports.processLiveTranscription = async (req, res) => {
    try {
        const { event_id, session_id, rtmp_url } = req.body;

        if (!session_id || !event_id) {
            return res.status(400).json({ error: "❌ session_id and event_id are required." });
        }

        let finalRtmpUrl = rtmp_url;
        if (!finalRtmpUrl) {
            const [sessionResult] = await db.execute("SELECT live_stream_url FROM sessions WHERE id = ?", [session_id]);
            if (sessionResult.length === 0) {
                return res.status(404).json({ error: "❌ Session not found" });
            }
            finalRtmpUrl = sessionResult[0].live_stream_url;
            if (!finalRtmpUrl) {
                return res.status(400).json({ error: "❌ RTMP URL not set for this session" });
            }
        }

        console.log("📡 Starting RTMP Transcription:", finalRtmpUrl);
        // Pass all three required arguments: RTMP URL, Session ID, Event ID.
        exec(`node process_audio.js "${finalRtmpUrl}" "${session_id}" "${event_id}"`, (error, stdout, stderr) => {
            if (error) {
                console.error("❌ Error processing audio:", error);
                // Do not send a response here since it was already sent.
                return;
            }
            console.log("Audio process started:", stdout);
        });

        res.json({ message: "✅ RTMP Transcription started successfully!" });
    } catch (error) {
        console.error("❌ Error processing RTMP transcription:", error);
        res.status(500).json({ error: "❌ Failed to process transcription." });
    }
};


// ✅ API Endpoint: Fetch Approved Transcriptions for a Session
exports.getSessionTranscriptions = async (req, res) => {
    try {
        const { session_id } = req.params;
        const [results] = await db.execute(
            "SELECT * FROM transcriptions WHERE session_id = ? AND transcription_status = 'approved'",
            [session_id]
        );
        res.json(results);
    } catch (error) {
        console.error("❌ Error fetching session transcriptions:", error);
        res.status(500).json({ error: "Database error", details: error });
    }
};


// ✅ API Endpoint: Fetch All Transcriptions
exports.getTranscriptions = async (req, res) => {
    try {
        const [results] = await db.execute("SELECT * FROM transcriptions");
        res.json(results);
    } catch (error) {
        console.error("❌ Error fetching transcriptions:", error);
        res.status(500).json({ error: "Database error", details: error });
    }
};
// ✅ API Endpoint: Approve Transcription
exports.approveTranscription = async (req, res) => {
    try {
        const { id } = req.params;

        await db.execute("UPDATE transcriptions SET transcription_status = 'approved' WHERE id = ?", [id]);

        res.json({ message: "✅ Transcription approved successfully!" });
    } catch (error) {
        console.error("❌ Error approving transcription:", error);
        res.status(500).json({ error: "Database error", details: error });
    }
};

// ✅ API Endpoint: Reject Transcription
exports.rejectTranscription = async (req, res) => {
    try {
        const { id } = req.params;

        await db.execute("UPDATE transcriptions SET transcription_status = 'rejected' WHERE id = ?", [id]);

        res.json({ message: "✅ Transcription rejected successfully!" });
    } catch (error) {
        console.error("❌ Error rejecting transcription:", error);
        res.status(500).json({ error: "Database error", details: error });
    }
};

exports.submitTranscription = async (req, res) => {
    try {
        const { event_id, session_id, transcript, transcript_ar, moderator_id } = req.body;
        if (!event_id || !session_id || !transcript) {
            return res.status(400).json({ error: "❌ Missing required fields: event_id, session_id, transcript." });
        }

        // Insert the transcription into the database
        await db.execute(
            `INSERT INTO transcriptions (event_id, session_id, transcript, transcript_ar, transcription_status, moderator_id) 
             VALUES (?, ?, ?, ?, 'pending', ?)`,
            [event_id, session_id, transcript, transcript_ar || "", moderator_id || null]
        );

        // Emit the newTranscription event to all connected clients.
        // Ensure that your server.js attaches the io instance to the Express app (e.g., app.set("io", io))
        const io = req.app.get("io");
        io.emit("newTranscription", { event_id, session_id, transcript, transcript_ar });

        res.json({ message: "✅ Transcription submitted successfully!" });
    } catch (err) {
        console.error("❌ Error submitting transcription:", err);
        res.status(500).json({ error: "Database error", details: err.message });
    }
};

// 📌 Fetch Single Transcription by ID
exports.getTranscriptionById = async (req, res) => {
    try {
        const { id } = req.params;

        // ✅ Fetch from Database
        const [result] = await db.execute("SELECT * FROM transcriptions WHERE id = ?", [id]);

        // ✅ Check if Transcription Exists
        if (result.length === 0) {
            return res.status(404).json({ message: "❌ Transcription not found" });
        }

        res.json(result[0]);
    } catch (err) {
        console.error("❌ Error fetching transcription:", err);
        res.status(500).json({ error: "Database error", details: err.message });
    }
};