import { FaceDetector, FilesetResolver } from '@mediapipe/tasks-vision';

let faceDetector = null;

export async function loadFaceDetector() {
    if (faceDetector) return;

    const vision = await FilesetResolver.forVisionTasks(
        'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm'
    );

    faceDetector = await FaceDetector.createFromOptions(vision, {
        baseOptions: {
            modelAssetPath: 'https://storage.googleapis.com/mediapipe-models/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite'
        },
        runningMode: 'IMAGE'
    });
}

// fixed: parameter was named 'File' (capital F) but used as 'file' below — caused ReferenceError
// that fell silently into the ComposeSheet catch block, allowing every upload through
export async function hasFace(file) {
    await loadFaceDetector();

    const objectUrl = URL.createObjectURL(file);
    const img = document.createElement('img');

    // fixed: onload/onerror must be assigned BEFORE setting img.src — if the object URL
    // resolves synchronously the load event fires before the handler was attached and
    // the Promise never settles, leaving detection running on an unloaded element
    await new Promise((resolve, reject) => {
        img.onload = resolve;
        img.onerror = () => reject(new Error('Image failed to load'));
        img.src = objectUrl;
    });

    const result = faceDetector.detect(img);
    URL.revokeObjectURL(objectUrl);

    return result.detections.length > 0;
}
