/**
 * ==================================================
 * Smart Attendance System
 * AI Controller
 * ==================================================
 * Handles all AI-related requests.
 *
 * Endpoints
 * ------------------------
 * GET     /health
 * POST    /detect
 * POST    /embed
 * POST    /train
 * POST    /recognize
 * ==================================================
 */

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."

            });

        }

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

        const aiResponse = await AIService.train(

            student_id,

            req.files

        );

        //---------------------------------------------
        // Save Average 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"

        });

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

        return res.status(200).json({

            success: true,

            message: "Student trained successfully.",

            data: aiResponse.data

        });

    }

    /**
     * ==================================================
     * 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."

            });

        }

        //---------------------------------------------
        // Recognition
        //---------------------------------------------

        const aiResponse = await AIService.recognize(

            req.file,

            students

        );

        //---------------------------------------------
        // Optional Recognition Service
        //---------------------------------------------

        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;