<?php

/**
 * JCOGS Image Pro - HAAR Face Detection Provider
 * Provider Architecture - Built-in Provider
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://JCOGS.net/
 * @since      Provider Architecture v1.0
 */

namespace JCOGSDesign\JCOGSImagePro\Service\Provider;

use JCOGSDesign\JCOGSImagePro\Service\FaceDetectionService;
use JCOGSDesign\JCOGSImagePro\Service\ServiceCache;

/**
 * HAAR Face Detection Provider
 * 
 * Built-in face detection provider using HAARPHP library.
 * This wraps the core FaceDetectionService to make it available
 * through the provider registry system.
 * 
 * Priority: 10 (baseline - companion add-ons should use higher priorities)
 */
class HaarFaceDetectionProvider implements FaceRecognitionProviderInterface
{
    /**
     * Face detection service instance
     * @var FaceDetectionService
     */
    private FaceDetectionService $service;
    
    /**
     * Constructor
     * 
     * @param FaceDetectionService|null $service Optional service instance (for testing)
     */
    public function __construct(?FaceDetectionService $service = null)
    {
        $this->service = $service ?? ServiceCache::face_detection();
    }
    
    /**
     * Get provider name
     * 
     * @return string Provider identifier
     */
    public function getName(): string
    {
        return 'core_haar';
    }
    
    /**
     * Get provider priority
     * 
     * Core HAARPHP implementation uses priority 10 as baseline.
     * Companion add-ons should use higher priorities (20+ for local, 100+ for cloud).
     * 
     * @return int Priority value
     */
    public function getPriority(): int
    {
        return 10;
    }
    
    /**
     * Check if provider is available
     * 
     * Built-in HAAR provider is always available since HAARPHP
     * is bundled with the core add-on.
     * 
     * @return bool Always true for core provider
     */
    public function isAvailable(): bool
    {
        return true;
    }
    
    /**
     * Detect faces using HAARPHP
     * 
     * Delegates to FaceDetectionService which handles:
     * - HAAR cascade detection
     * - Fallback to skin tone detection
     * - Cross-sensitivity caching
     * - Quality preset configuration
     * 
     * @param resource|\GdImage $image GD image resource
     * @param array $options Detection options:
     *   - sensitivity: int (1-9, legacy compatible)
     *   - quality: string ('fast'|'balanced'|'accurate')
     *   - max_faces: int|null (not used by HAAR, but accepted for compatibility)
     *   - min_confidence: float (not used by HAAR, but accepted for compatibility)
     * 
     * @return array Face regions with metadata:
     *   [
     *     [
     *       'x' => int,           // Top-left X coordinate (aliased from min_x)
     *       'y' => int,           // Top-left Y coordinate (aliased from min_y)
     *       'width' => int,       // Face width in pixels
     *       'height' => int,      // Face height in pixels
     *       'confidence' => float, // Fixed at 0.8 (HAAR doesn't provide confidence)
     *       'metadata' => []      // Empty - HAAR doesn't provide additional metadata
     *     ],
     *     // ... additional faces
     *   ]
     * 
     * @throws \Exception on detection failure
     */
    public function detectFaces($image, array $options = []): array
    {
        // Extract options with defaults
        $sensitivity = $options['sensitivity'] ?? 3;
        $quality = $options['quality'] ?? 'balanced';
        
        // Call core detection service
        $face_regions = $this->service->detect_faces($image, $sensitivity, $quality);
        
        // Transform to provider interface format
        // FaceDetectionService returns: ['min_x', 'min_y', 'max_x', 'max_y', 'width', 'height']
        // Provider interface expects: ['x', 'y', 'width', 'height', 'confidence', 'metadata']
        
        $formatted_faces = [];
        foreach ($face_regions as $region) {
            $formatted_faces[] = [
                'x' => $region['min_x'],
                'y' => $region['min_y'],
                'width' => $region['width'],
                'height' => $region['height'],
                'confidence' => 0.8, // HAAR doesn't provide confidence scores, use reasonable default
                'metadata' => [], // HAAR doesn't provide additional metadata
                
                // Include original format for backward compatibility
                'min_x' => $region['min_x'],
                'min_y' => $region['min_y'],
                'max_x' => $region['max_x'],
                'max_y' => $region['max_y'],
            ];
        }
        
        return $formatted_faces;
    }
    
    /**
     * Get provider capabilities
     * 
     * HAAR detection only provides bounding boxes - no additional metadata.
     * 
     * @return array Capability flags (all false for HAAR)
     */
    public function getCapabilities(): array
    {
        return [
            'emotions' => false,
            'age_estimation' => false,
            'gender' => false,
            'landmarks' => false,
            'pose' => false,
            'quality' => false,
            'attributes' => false,
        ];
    }
    
    /**
     * Get estimated cost per detection
     * 
     * @return float|null Always null (HAAR is free/included)
     */
    public function getCostPerDetection(): ?float
    {
        return null; // Free - included with core add-on
    }
}
