/**
 * ==================================================
 * Smart Attendance System
 * AI Controller
 * ==================================================
 */

const db = require("../config/db");

const AIService = require("../services/ai/ai.service");
const EmbeddingService = require("../services/embedding.service");
const RecognitionService = require("../services/recognition.service");

class AIController {

    /**
     * ==================================================
     * Health Check
     * ==================================================
     */

    static async health(req, res) {

        const result = await AIService.health();

        return res.status(200).json(result);

    }

    /**
     * ==================================================
     * Detect Face
     * ==================================================
     */

    static async detect(req, res) {

        if (!req.file) {

            return res.status(400).json({

                success: false,

                message: "Image is required."

            });

        }

        const result = await AIService.detect(req.file);

        return res.status(200).json(result);

    }

    /**
     * ==================================================
     * Generate Face Embedding
     * ==================================================
     */

    static async embed(req, res) {

        if (!req.file) {

            return res.status(400).json({

                success: false,

                message: "Image is required."

            });

        }

        const result = await AIService.embed(req.file);

        return res.status(200).json(result);

    }

    /**
     * ==================================================
     * Train Student
     * ==================================================
     */

    static async train(req, res) {

        const { student_id } = req.body;

        if (!student_id) {

            return res.status(400).json({

                success: false,

                message: "Student ID is required."

            });

        }

        if (!req.files || req.files.length === 0) {

            return res.status(400).json({

                success: false,

                message: "Training images are required."

            });

        }

        try {

            //--------------------------------------------------
            // Verify Student Exists
            //--------------------------------------------------

            const [student] = await db.query(

                `SELECT id, student_id, full_name
                 FROM students
                 WHERE student_id=?`,

                [student_id]

            );

            if (!student.length) {

                return res.status(404).json({

                    success: false,

                    message: "Student not found."

                });

            }

            //--------------------------------------------------
            // Mark Training Started
            //--------------------------------------------------

            await db.query(

                `UPDATE students
                 SET
                    training_status='training'
                 WHERE student_id=?`,

                [student_id]

            );

            //--------------------------------------------------
            // Python AI Training
            //--------------------------------------------------

            const aiResponse = await AIService.train(

                student_id,

                req.files

            );

            //--------------------------------------------------
            // Validate AI Response
            //--------------------------------------------------

            if (

                !aiResponse ||

                !aiResponse.success ||

                !aiResponse.data

            ) {

                throw new Error(

                    "AI Training failed."

                );

            }

            //--------------------------------------------------
            // Save Embedding
            //--------------------------------------------------

            await EmbeddingService.save({

                student_id:

                    aiResponse.data.student_id,

                average_embedding:

                    aiResponse.data.average_embedding,

                trained_images:

                    aiResponse.data.embeddings_generated,

                embedding_dimension:

                    aiResponse.data.average_embedding.length,

                ai_model:

                    "buffalo_l"

            });

            //--------------------------------------------------
            // Update Student Status
            //--------------------------------------------------

            await db.query(

                `UPDATE students
                 SET

                    face_trained = 1,

                    training_status = 'trained',

                    face_trained_at = NOW(),

                    trained_images = ?,

                    embedding_dimension = ?,

                    ai_model = ?

                 WHERE student_id=?`,

                [

                    aiResponse.data.embeddings_generated,

                    aiResponse.data.average_embedding.length,

                    "buffalo_l",

                    student_id

                ]

            );
                        //--------------------------------------------------
            // Success Response
            //--------------------------------------------------

            return res.status(200).json({

                success: true,

                message: "Student trained successfully.",

                data: {

                    student_id:

                        aiResponse.data.student_id,

                    embeddings_generated:

                        aiResponse.data.embeddings_generated,

                    average_embedding:

                        aiResponse.data.average_embedding,

                    embedding_dimension:

                        aiResponse.data.average_embedding.length,

                    ai_model:

                        "buffalo_l",

                    training_status:

                        "trained"

                }

            });

        }

        catch (error) {

            //--------------------------------------------------
            // Update Student Status
            //--------------------------------------------------

            try {

                await db.query(

                    `UPDATE students
                     SET
                        training_status='failed'
                     WHERE student_id=?`,

                    [student_id]

                );

            }

            catch (dbError) {

                console.error(

                    "Database Update Error:",

                    dbError.message

                );

            }

            console.error(

                "AI Training Error:",

                error.message

            );

            return res.status(500).json({

                success: false,

                message:

                    error.message ||

                    "Training failed."

            });

        }

    }

    /**
     * ==================================================
     * Recognize Student
     * ==================================================
     */

    static async recognize(req, res) {

        if (!req.file) {

            return res.status(400).json({

                success: false,

                message: "Recognition image is required."

            });

        }

        //--------------------------------------------------
        // Load Embeddings
        //--------------------------------------------------

        const students = await EmbeddingService.getAll();

        if (!students.length) {

            return res.status(404).json({

                success: false,

                message: "No trained students found."

            });

        }

        //--------------------------------------------------
        // Python Recognition
        //--------------------------------------------------

        const aiResponse = await AIService.recognize(

            req.file,

            students

        );

        //--------------------------------------------------
        // Optional Recognition Log
        //--------------------------------------------------

        if (

            RecognitionService &&

            typeof RecognitionService.log === "function"

        ) {

            await RecognitionService.log(

                aiResponse.data

            );

        }

        //--------------------------------------------------
        // Response
        //--------------------------------------------------

        return res.status(200).json({

            success: true,

            message: "Recognition completed.",

            data: aiResponse.data

        });

    }

}

module.exports = AIController;