/**
 * ==================================================
 * Smart Attendance System
 * Recognition Service
 * ==================================================
 * Coordinates the face recognition workflow.
 *
 * Responsibilities
 * ----------------
 * ✓ Load registered face embeddings
 * ✓ Prepare recognition payload
 * ✓ Call Python AI Recognition API
 * ✓ Validate AI response
 * * (Student validation will be added later)
 * * (Attendance marking will be added later)
 * * (NFC verification will be added later)
 * ==================================================
 */

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

class RecognitionService {

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

    static async recognize(imagePath) {

        try {

            console.log("\n========================================");
            console.log("Recognition Service");
            console.log("========================================");

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

            console.log("Loading registered embeddings...");

            const embeddings =
                await EmbeddingService.getAll();

            if (!embeddings || embeddings.length === 0) {

                return {

                    success: false,

                    message:
                        "No registered students found.",

                    data: null

                };

            }

            console.log(
                `Loaded ${embeddings.length} registered students.`
            );

            //--------------------------------------
            // Prepare Payload for Python AI
            //--------------------------------------

            const students = embeddings.map(student => ({

                student_id: student.student_id,

                embedding: student.average_embedding

            }));

            //--------------------------------------
            // Call Python Recognition API
            //--------------------------------------

            console.log("Calling Python AI...");

            const aiResponse =
                await AIService.recognize(

                    imagePath,

                    students

                );

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

            if (!aiResponse) {

                return {

                    success: false,

                    message:
                        "No response received from AI service.",

                    data: null

                };

            }

            if (!aiResponse.success) {

                return {

                    success: false,

                    message:
                        aiResponse.message ||
                        "Recognition failed.",

                    data: aiResponse.data || null

                };

            }

            //--------------------------------------
            // Recognition Completed
            //--------------------------------------

            console.log("Recognition completed.");

            if (
                aiResponse.data &&
                aiResponse.data.student_id
            ) {

                console.log(
                    `Matched Student : ${aiResponse.data.student_id}`
                );

            } else {

                console.log(
                    "No matching student."
                );

            }

            return {

                success: true,

                message:
                    aiResponse.message,

                data:
                    aiResponse.data

            };

        }

        catch (error) {

            console.error(
                "\nRecognition Service Error:"
            );

            console.error(error.message);

            return {

                success: false,

                message:
                    error.message ||

                    "Recognition failed.",

                data: null

            };

        }

    }

}

module.exports = RecognitionService;