<?php
/**
 * CLAWS AI Integration Class
 * Handles AI-powered photo analysis for cat coat and color detection
 */

if (!defined('ABSPATH')) {
    exit;
}

class CLAWS_AI {
    
    private static $instance = null;
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Add AJAX endpoint for AI testing
        add_action('wp_ajax_claws_test_ai_service', array($this, 'test_ai_service'));
        add_action('wp_ajax_claws_analyze_photo', array($this, 'analyze_photo'));
    }
    
    /**
     * Check if AI is enabled and configured
     */
    public function is_enabled() {
        return get_option('claws_ai_enabled', 0) == 1 && !empty(get_option('claws_ai_provider', ''));
    }
    
    /**
     * Get AI configuration
     */
    private function get_config() {
        return array(
            'enabled' => get_option('claws_ai_enabled', 0),
            'provider' => get_option('claws_ai_provider', ''),
            'api_key' => get_option('claws_ai_api_key', ''),
            'custom_url' => get_option('claws_ai_custom_url', ''),
            'confidence_threshold' => get_option('claws_ai_confidence_threshold', 0.7),
            'fallback' => get_option('claws_ai_fallback', 'mock')
        );
    }
    
    /**
     * Analyze uploaded photo for coat and color
     */
    public function analyze_photo() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'claws_ai_nonce')) {
            wp_die('Security check failed');
        }
        
        if (!$this->is_enabled()) {
            wp_send_json_error('AI analysis is not enabled or configured');
        }
        
        // Get uploaded image data
        if (!isset($_FILES['image'])) {
            wp_send_json_error('No image uploaded');
        }
        
        $image_file = $_FILES['image'];
        
        // Validate file
        if ($image_file['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error('Image upload failed');
        }
        
        // Check file type
        $allowed_types = array('image/jpeg', 'image/png', 'image/webp');
        if (!in_array($image_file['type'], $allowed_types)) {
            wp_send_json_error('Invalid file type. Please upload JPG, PNG, or WebP images.');
        }
        
        // Check file size (5MB max)
        if ($image_file['size'] > 5 * 1024 * 1024) {
            wp_send_json_error('File too large. Maximum size is 5MB.');
        }
        
        $config = $this->get_config();
        
        try {
            $result = $this->call_ai_service($image_file['tmp_name'], $config);
            
            if ($result && $result['confidence'] >= $config['confidence_threshold']) {
                wp_send_json_success($result);
            } else {
                // Handle fallback
                $fallback_result = $this->handle_fallback($config['fallback']);
                wp_send_json_success($fallback_result);
            }
            
        } catch (Exception $e) {
            error_log('CLAWS AI Error: ' . $e->getMessage());
            
            // Handle fallback
            $fallback_result = $this->handle_fallback($config['fallback']);
            if ($fallback_result) {
                wp_send_json_success($fallback_result);
            } else {
                wp_send_json_error('AI analysis failed: ' . $e->getMessage());
            }
        }
    }
    
    /**
     * Call the configured AI service
     */
    private function call_ai_service($image_path, $config) {
        switch ($config['provider']) {
            case 'nyckel':
                return $this->call_nyckel_api($image_path, $config['api_key']);
                
            case 'siwalu':
                return $this->call_siwalu_api($image_path, $config['api_key']);
                
            case 'vision':
                return $this->call_google_vision_api($image_path, $config['api_key']);
                
            case 'custom':
                return $this->call_custom_api($image_path, $config['api_key'], $config['custom_url']);
                
            default:
                throw new Exception('Unknown AI provider: ' . $config['provider']);
        }
    }
    
    /**
     * Call Nyckel API for cat breed detection
     */
    private function call_nyckel_api($image_path, $api_key) {
        $url = 'https://www.nyckel.com/v1/functions/cat-breed-identifier/invoke';
        
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
            ),
            'body' => array(
                'data' => base64_encode(file_get_contents($image_path))
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            throw new Exception('Nyckel API request failed: ' . $response->get_error_message());
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['labelName'])) {
            throw new Exception('Invalid response from Nyckel API');
        }
        
        return $this->normalize_nyckel_response($data);
    }
    
    /**
     * Call Siwalu API for animal breed recognition
     */
    private function call_siwalu_api($image_path, $api_key) {
        $url = 'https://api.siwalu.com/v1/animal/breed';
        
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'multipart/form-data'
            ),
            'body' => array(
                'image' => new CURLFile($image_path),
                'animal_type' => 'cat'
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            throw new Exception('Siwalu API request failed: ' . $response->get_error_message());
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['breed'])) {
            throw new Exception('Invalid response from Siwalu API');
        }
        
        return $this->normalize_siwalu_response($data);
    }
    
    /**
     * Call Google Vision API
     */
    private function call_google_vision_api($image_path, $api_key) {
        $url = 'https://vision.googleapis.com/v1/images:annotate?key=' . $api_key;
        
        $image_data = base64_encode(file_get_contents($image_path));
        
        $request_body = array(
            'requests' => array(
                array(
                    'image' => array(
                        'content' => $image_data
                    ),
                    'features' => array(
                        array('type' => 'LABEL_DETECTION', 'maxResults' => 10),
                        array('type' => 'IMAGE_PROPERTIES', 'maxResults' => 10)
                    )
                )
            )
        );
        
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'body' => wp_json_encode($request_body),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            throw new Exception('Google Vision API request failed: ' . $response->get_error_message());
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['responses'][0])) {
            throw new Exception('Invalid response from Google Vision API');
        }
        
        return $this->normalize_google_vision_response($data['responses'][0]);
    }
    
    /**
     * Call custom API endpoint
     */
    private function call_custom_api($image_path, $api_key, $url) {
        $image_data = base64_encode(file_get_contents($image_path));
        
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => wp_json_encode(array(
                'image' => $image_data,
                'task' => 'cat_analysis'
            )),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            throw new Exception('Custom API request failed: ' . $response->get_error_message());
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data) {
            throw new Exception('Invalid response from custom API');
        }
        
        return $this->normalize_custom_response($data);
    }
    
    /**
     * Normalize different API responses to standard format
     */
    private function normalize_nyckel_response($data) {
        // Map Nyckel breed names to our coat types
        $breed_to_coat = array(
            'Persian' => 'Domestic Long Hair',
            'Maine Coon' => 'Domestic Long Hair',
            'American Shorthair' => 'Domestic Short Hair',
            'British Shorthair' => 'Domestic Short Hair',
            'Russian Blue' => 'Domestic Short Hair'
        );
        
        $breed = $data['labelName'] ?? 'Unknown';
        $coat = $breed_to_coat[$breed] ?? 'Domestic Short Hair';
        
        return array(
            'coat' => $coat,
            'color' => $this->extract_color_from_breed($breed),
            'confidence' => $data['confidence'] ?? 0.5,
            'source' => 'nyckel'
        );
    }
    
    private function normalize_siwalu_response($data) {
        return array(
            'coat' => $this->map_breed_to_coat($data['breed']),
            'color' => $data['color'] ?? 'Mixed',
            'confidence' => $data['confidence'] ?? 0.5,
            'source' => 'siwalu'
        );
    }
    
    private function normalize_google_vision_response($data) {
        $labels = $data['labelAnnotations'] ?? array();
        
        // Look for cat-related labels
        $coat = 'Domestic Short Hair';
        $color = 'Mixed';
        $confidence = 0.3;
        
        foreach ($labels as $label) {
            $description = strtolower($label['description']);
            $score = $label['score'];
            
            if (strpos($description, 'long') !== false && strpos($description, 'hair') !== false) {
                $coat = 'Domestic Long Hair';
                $confidence = max($confidence, $score);
            } elseif (strpos($description, 'short') !== false && strpos($description, 'hair') !== false) {
                $coat = 'Domestic Short Hair';
                $confidence = max($confidence, $score);
            }
            
            // Extract color information
            $colors = array('black', 'white', 'orange', 'gray', 'brown', 'tabby', 'calico');
            foreach ($colors as $c) {
                if (strpos($description, $c) !== false) {
                    $color = ucfirst($c);
                    break;
                }
            }
        }
        
        return array(
            'coat' => $coat,
            'color' => $color,
            'confidence' => $confidence,
            'source' => 'google_vision'
        );
    }
    
    private function normalize_custom_response($data) {
        return array(
            'coat' => $data['coat'] ?? 'Domestic Short Hair',
            'color' => $data['color'] ?? 'Mixed',
            'confidence' => $data['confidence'] ?? 0.5,
            'source' => 'custom'
        );
    }
    
    /**
     * Handle fallback when AI fails or confidence is too low
     */
    private function handle_fallback($fallback_type) {
        switch ($fallback_type) {
            case 'mock':
                return $this->generate_mock_result();
                
            case 'manual':
                return array(
                    'coat' => '',
                    'color' => '',
                    'confidence' => 0,
                    'message' => 'Please enter coat type and color manually',
                    'source' => 'manual'
                );
                
            case 'disable':
            default:
                return false;
        }
    }
    
    /**
     * Generate mock AI result (same as before)
     */
    private function generate_mock_result() {
        $coats = array('Domestic Short Hair', 'Domestic Medium Hair', 'Domestic Long Hair');
        $colors = array(
            'Orange tabby', 'Black', 'Black and white', 'Gray tabby', 'Calico', 
            'Tortoiseshell', 'White', 'Brown tabby', 'Tuxedo', 'Gray and white',
            'Orange and white', 'Siamese pointed', 'Russian blue', 'Cream'
        );
        
        return array(
            'coat' => $coats[array_rand($coats)],
            'color' => $colors[array_rand($colors)],
            'confidence' => 0.8,
            'source' => 'mock'
        );
    }
    
    /**
     * Test AI service connection
     */
    public function test_ai_service() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'claws_test_ai')) {
            wp_die('Security check failed');
        }
        
        $provider = sanitize_text_field($_POST['provider']);
        $api_key = sanitize_text_field($_POST['api_key']);
        $custom_url = esc_url_raw($_POST['custom_url']);
        
        // Create a test image (1x1 pixel PNG)
        $test_image = tempnam(sys_get_temp_dir(), 'claws_test_');
        $png_data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==');
        file_put_contents($test_image, $png_data);
        
        try {
            $config = array(
                'provider' => $provider,
                'api_key' => $api_key,
                'custom_url' => $custom_url
            );
            
            $result = $this->call_ai_service($test_image, $config);
            
            unlink($test_image); // Clean up
            
            wp_send_json_success('Connection successful');
            
        } catch (Exception $e) {
            unlink($test_image); // Clean up
            wp_send_json_error($e->getMessage());
        }
    }
    
    /**
     * Helper functions
     */
    private function map_breed_to_coat($breed) {
        $long_hair_breeds = array('Persian', 'Maine Coon', 'Norwegian Forest', 'Ragdoll');
        $medium_hair_breeds = array('American Curl', 'Selkirk Rex');
        
        foreach ($long_hair_breeds as $lh_breed) {
            if (stripos($breed, $lh_breed) !== false) {
                return 'Domestic Long Hair';
            }
        }
        
        foreach ($medium_hair_breeds as $mh_breed) {
            if (stripos($breed, $mh_breed) !== false) {
                return 'Domestic Medium Hair';
            }
        }
        
        return 'Domestic Short Hair';
    }
    
    private function extract_color_from_breed($breed) {
        if (stripos($breed, 'Russian Blue') !== false) return 'Russian blue';
        if (stripos($breed, 'Orange') !== false) return 'Orange tabby';
        if (stripos($breed, 'Calico') !== false) return 'Calico';
        if (stripos($breed, 'Tortoiseshell') !== false) return 'Tortoiseshell';
        if (stripos($breed, 'Tuxedo') !== false) return 'Tuxedo';
        
        return 'Mixed';
    }
}