<?php

if (!defined('WPINC')) {
    die;
}

class Aysa_Image_Processor {
    
    private $api_base_url;
    private $confidence_scorer;
    private $audit_logger;
    
    public function __construct() {
        $this->api_base_url = defined('AYSA_API_BASE_URL') ? AYSA_API_BASE_URL : 'https://api.aysa.ai/api/';
        $this->confidence_scorer = new Aysa_Confidence_Scorer();
        $this->audit_logger = new Aysa_Audit_Logger();
    }
    
    public function process($job_data) {
        $attachment_id = $job_data['attachment_id'];
        
        if (!wp_attachment_is_image($attachment_id)) {
            return new WP_Error('invalid_attachment', 'Attachment is not an image');
        }
        
        $existing_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
        if (!empty($existing_alt)) {
            return new WP_Error('alt_exists', 'Image already has alt text');
        }
        
        $image_data = $this->prepare_image_data($attachment_id, $job_data);
        $generated_content = $this->generate_image_content($image_data);
        
        if (is_wp_error($generated_content)) {
            return $generated_content;
        }
        
        $confidence_result = $this->confidence_scorer->calculate_image_confidence($image_data, $generated_content);
        
        $automation_config = get_option('aysa_automation_config', array());
        $threshold = $automation_config['confidence_threshold'] ?? 0.7;
        
        if ($confidence_result['score'] >= $threshold) {
            return $this->apply_image_optimization($attachment_id, $generated_content, $confidence_result);
        } else {
            return $this->queue_for_review($attachment_id, $generated_content, $confidence_result);
        }
    }
    
    private function prepare_image_data($attachment_id, $job_data) {
        $attachment = get_post($attachment_id);
        $metadata = wp_get_attachment_metadata($attachment_id);
        
        $image_data = array(
            'id' => $attachment_id,
            'filename' => basename($attachment->guid),
            'title' => $attachment->post_title,
            'description' => $attachment->post_content,
            'caption' => $attachment->post_excerpt,
            'mime_type' => $attachment->post_mime_type,
            'url' => wp_get_attachment_url($attachment_id)
        );
        
        if ($metadata) {
            $image_data['width'] = $metadata['width'] ?? 0;
            $image_data['height'] = $metadata['height'] ?? 0;
            $image_data['file_size'] = $metadata['filesize'] ?? 0;
        }
        
        if (isset($job_data['context'])) {
            $image_data['context'] = $job_data['context'];
        }
        
        return $image_data;
    }
    
    private function generate_image_content($image_data) {
        $api_url = $this->api_base_url . 'ImageAnalysis/generateAltText';
        
        $request_data = array(
            'imageUrl' => $image_data['url'],
            'context' => $image_data['context'] ?? array(),
            'filename' => $image_data['filename'],
            'existingTitle' => $image_data['title']
        );
        
        $response = wp_remote_post($api_url, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ),
            'body' => wp_json_encode($request_data)
        ));
        
        if (is_wp_error($response)) {
            return new WP_Error('api_error', 'Failed to connect to image analysis API: ' . $response->get_error_message());
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return new WP_Error('api_error', 'Image analysis API returned error code: ' . $response_code);
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['altText'])) {
            return new WP_Error('invalid_response', 'Invalid response from image analysis API');
        }
        
        return array(
            'alt_text' => sanitize_text_field($data['altText']),
            'title' => sanitize_text_field($data['title'] ?? ''),
            'description' => sanitize_textarea_field($data['description'] ?? ''),
            'api_confidence' => floatval($data['confidence'] ?? 0.5)
        );
    }
    
    private function apply_image_optimization($attachment_id, $generated_content, $confidence_result) {
        $old_data = array(
            'alt_text' => get_post_meta($attachment_id, '_wp_attachment_image_alt', true),
            'title' => get_the_title($attachment_id),
            'description' => get_post_field('post_content', $attachment_id)
        );
        
        $success = true;
        $applied_changes = array();
        
        if (!empty($generated_content['alt_text'])) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', $generated_content['alt_text']);
            $applied_changes['alt_text'] = $generated_content['alt_text'];
        }
        
        if (!empty($generated_content['title']) && empty($old_data['title'])) {
            wp_update_post(array(
                'ID' => $attachment_id,
                'post_title' => $generated_content['title']
            ));
            $applied_changes['title'] = $generated_content['title'];
        }
        
        if (!empty($generated_content['description']) && empty($old_data['description'])) {
            wp_update_post(array(
                'ID' => $attachment_id,
                'post_content' => $generated_content['description']
            ));
            $applied_changes['description'] = $generated_content['description'];
        }
        
        $this->audit_logger->log_action(
            'image_optimization',
            $attachment_id,
            'attachment',
            $old_data,
            $applied_changes,
            $confidence_result['score'],
            true
        );
        
        return array(
            'success' => $success,
            'applied_changes' => $applied_changes,
            'confidence_score' => $confidence_result['score'],
            'message' => 'Image optimization applied automatically'
        );
    }
    
    private function queue_for_review($attachment_id, $generated_content, $confidence_result) {
        $review_data = array(
            'attachment_id' => $attachment_id,
            'generated_content' => $generated_content,
            'confidence_score' => $confidence_result['score'],
            'confidence_factors' => $confidence_result['factors'],
            'recommendation' => $confidence_result['recommendation'],
            'created_at' => current_time('mysql')
        );
        
        $existing_reviews = get_option('aysa_pending_image_reviews', array());
        $existing_reviews[$attachment_id] = $review_data;
        update_option('aysa_pending_image_reviews', $existing_reviews);
        
        return array(
            'success' => true,
            'queued_for_review' => true,
            'confidence_score' => $confidence_result['score'],
            'message' => 'Image optimization queued for manual review due to low confidence'
        );
    }
    
    public function get_pending_reviews() {
        return get_option('aysa_pending_image_reviews', array());
    }
    
    public function approve_review($attachment_id) {
        $pending_reviews = get_option('aysa_pending_image_reviews', array());
        
        if (!isset($pending_reviews[$attachment_id])) {
            return new WP_Error('review_not_found', 'Pending review not found');
        }
        
        $review_data = $pending_reviews[$attachment_id];
        $result = $this->apply_image_optimization(
            $attachment_id, 
            $review_data['generated_content'], 
            array('score' => $review_data['confidence_score'])
        );
        
        unset($pending_reviews[$attachment_id]);
        update_option('aysa_pending_image_reviews', $pending_reviews);
        
        return $result;
    }
    
    public function reject_review($attachment_id) {
        $pending_reviews = get_option('aysa_pending_image_reviews', array());
        
        if (!isset($pending_reviews[$attachment_id])) {
            return new WP_Error('review_not_found', 'Pending review not found');
        }
        
        unset($pending_reviews[$attachment_id]);
        update_option('aysa_pending_image_reviews', $pending_reviews);
        
        return array(
            'success' => true,
            'message' => 'Image optimization review rejected'
        );
    }
}
