<?php

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

class Aysa_Domain_Authority_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/';
        
        if (class_exists('Aysa_Confidence_Scorer')) {
            $this->confidence_scorer = new Aysa_Confidence_Scorer();
        } else {
            aysa_debug_log('Aysa_Confidence_Scorer class not found');
        }
        
        if (class_exists('Aysa_Audit_Logger')) {
            $this->audit_logger = new Aysa_Audit_Logger();
        } else {
            aysa_debug_log('Aysa_Audit_Logger class not found');
        }
    }
    
    public function process($job_data) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Starting queue processing for project: ' . $job_data['project_id']);
        $project_id = $job_data['project_id'];
        $task_data = $job_data['task_data'];
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task data: ' . json_encode($task_data));
        
        if (!$this->confidence_scorer) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Confidence scorer not available, cannot process task');
            return new WP_Error('confidence_scorer_unavailable', 'Confidence scorer not available');
        }
        
        $confidence_result = $this->confidence_scorer->calculate_domain_authority_confidence($task_data);
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Confidence calculation result: ' . json_encode($confidence_result));
        
        $automation_config = get_option('aysa_automation_config', array());
        $threshold = $automation_config['confidence_threshold'] ?? 0.7;
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Using confidence threshold: ' . $threshold);
        
        if ($confidence_result['score'] >= $threshold) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Confidence score ' . $confidence_result['score'] . ' meets threshold, applying task automatically');
            return $this->apply_domain_authority_task($project_id, $task_data, $confidence_result);
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Confidence score ' . $confidence_result['score'] . ' below threshold, queuing for review');
            return $this->queue_for_review($project_id, $task_data, $confidence_result);
        }
    }
    
    private function apply_domain_authority_task($project_id, $task_data, $confidence_result) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Applying domain authority task for project: ' . $project_id);
        
        // Create task in ResearchTasks API
        $task_created = $this->create_research_task($project_id, $task_data);
        
        if (is_wp_error($task_created)) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Failed to create ResearchTask: ' . $task_created->get_error_message());
            return $task_created;
        }
        
        if ($this->audit_logger) {
            $this->audit_logger->log_action(
                'domain_authority_task',
                $project_id,
                'project',
                array(),
                $task_data,
                $confidence_result['score'],
                true
            );
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task application logged to audit trail');
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Audit logger not available, skipping audit log');
        }
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Domain authority task applied successfully and created in ResearchTasks');
        return array(
            'success' => true,
            'applied_changes' => $task_data,
            'confidence_score' => $confidence_result['score'],
            'task_id' => $task_created,
            'message' => 'Domain authority task approved and created successfully'
        );
    }
    
    private function queue_for_review($project_id, $task_data, $confidence_result) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Queuing task for manual review, project: ' . $project_id);
        
        $review_data = array(
            'project_id' => $project_id,
            'task_data' => $task_data,
            'confidence_score' => $confidence_result['score'],
            'confidence_factors' => $confidence_result['factors'],
            'recommendation' => $confidence_result['recommendation'],
            'created_at' => current_time('mysql')
        );
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Review data prepared: ' . json_encode($review_data));
        
        $existing_reviews = get_option('aysa_pending_domain_authority_reviews', array());
        $existing_reviews[$project_id] = $review_data;
        $update_result = update_option('aysa_pending_domain_authority_reviews', $existing_reviews);
        
        if ($update_result) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task successfully queued for review');
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Warning: Failed to update pending reviews option');
        }
        
        return array(
            'success' => true,
            'queued_for_review' => true,
            'confidence_score' => $confidence_result['score'],
            'message' => 'Domain authority task queued for manual review due to low confidence'
        );
    }
    
    public function get_pending_reviews() {
        $reviews = get_option('aysa_pending_domain_authority_reviews', array());
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Retrieved ' . count($reviews) . ' pending reviews from database');
        return $reviews;
    }
    
    public function approve_review($project_id) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Processing review approval for project: ' . $project_id);
        $pending_reviews = get_option('aysa_pending_domain_authority_reviews', array());
        
        if (!isset($pending_reviews[$project_id])) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Review not found for project: ' . $project_id);
            return new WP_Error('review_not_found', 'Pending review not found');
        }
        
        $review_data = $pending_reviews[$project_id];
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Applying approved task for project: ' . $project_id);
        $result = $this->apply_domain_authority_task(
            $project_id, 
            $review_data['task_data'], 
            array('score' => $review_data['confidence_score'])
        );
        
        unset($pending_reviews[$project_id]);
        $update_result = update_option('aysa_pending_domain_authority_reviews', $pending_reviews);
        
        if ($update_result) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Review approval completed and removed from pending list');
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Warning: Failed to remove approved review from pending list');
        }
        
        return $result;
    }
    
    public function reject_review($project_id) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Processing review rejection for project: ' . $project_id);
        $pending_reviews = get_option('aysa_pending_domain_authority_reviews', array());
        
        if (!isset($pending_reviews[$project_id])) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Review not found for project: ' . $project_id);
            return new WP_Error('review_not_found', 'Pending review not found');
        }
        
        unset($pending_reviews[$project_id]);
        $update_result = update_option('aysa_pending_domain_authority_reviews', $pending_reviews);
        
        if ($update_result) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Review rejection completed and removed from pending list');
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Warning: Failed to remove rejected review from pending list');
        }
        
        return array(
            'success' => true,
            'message' => 'Domain authority task review rejected'
        );
    }
    
    /**
     * Create a task in ResearchTasks API
     */
    private function create_research_task($project_id, $task_data) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Creating ResearchTask for project: ' . $project_id);
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task data: ' . json_encode($task_data));
        
        $task_title = $task_data['title'] ?? 'Domain Authority Optimization Task';
        $task_description = $task_data['description'] ?? 'Approved domain authority task from automation review';
        
        // Check if task already exists first
        $existing_task_check = wp_remote_get(
            rtrim($this->api_base_url, '/') . '/ResearchTasks/ByProject/' . $project_id,
            array(
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/json'
                )
            )
        );
        
        if (!is_wp_error($existing_task_check) && wp_remote_retrieve_response_code($existing_task_check) === 200) {
            $existing_tasks = json_decode(wp_remote_retrieve_body($existing_task_check), true);
            
            if (is_array($existing_tasks)) {
                // Check if task with same title already exists and is not deleted
                foreach ($existing_tasks as $existing_task) {
                    if ($existing_task['title'] === $task_title && 
                        isset($existing_task['status']) && 
                        $existing_task['status'] !== 'deleted') {
                        
                        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task already exists, updating status to in_progress: ' . $existing_task['id']);
                        
                        // Update existing task to in_progress
                        $update_response = wp_remote_request(
                            rtrim($this->api_base_url, '/') . '/ResearchTasks/' . $existing_task['id'],
                            array(
                                'method' => 'PUT',
                                'timeout' => 30,
                                'headers' => array(
                                    'Content-Type' => 'application/json'
                                ),
                                'body' => json_encode(array(
                                    'status' => 'in_progress',
                                    'title' => $task_title,
                                    'description' => $task_description,
                                    'flag' => 'isAi',
                                    'percent' => 0,
                                    'type' => 'domain-authority'
                                ))
                            )
                        );
                        
                        if (is_wp_error($update_response)) {
                            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Error updating existing task: ' . $update_response->get_error_message());
                            return new WP_Error('update_failed', 'Failed to update existing task');
                        }
                        
                        return $existing_task['id'];
                    }
                }
            }
        }
        
        // Create new task
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Creating new ResearchTask with title: ' . $task_title);
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task will include: percent=0, type=domain-authority');
        
        $response = wp_remote_post(
            rtrim($this->api_base_url, '/') . '/ResearchTasks',
            array(
                'timeout' => 30,
                'headers' => array(
                    'Content-Type' => 'application/json'
                ),
                'body' => json_encode(array(
                    'projectId' => intval($project_id),
                    'title' => $task_title,
                    'description' => $task_description,
                    'status' => 'in_progress',
                    'flag' => 'isAi',
                    'percent' => 0,
                    'type' => 'domain-authority'
                ))
            )
        );
        
        if (is_wp_error($response)) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] HTTP error creating task: ' . $response->get_error_message());
            return new WP_Error('http_error', 'Failed to create task: ' . $response->get_error_message());
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] API response code: ' . $response_code);
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] API response body: ' . $response_body);
        
        if ($response_code !== 200 && $response_code !== 201) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] API returned error code: ' . $response_code);
            return new WP_Error('api_error', 'API returned error code: ' . $response_code);
        }
        
        $task_data_response = json_decode($response_body, true);
        
        if (isset($task_data_response['id'])) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task created successfully with ID: ' . $task_data_response['id']);
            return $task_data_response['id'];
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Task created but no ID returned. Response: ' . $response_body);
            return true; // Task was created successfully even if we don't have the ID
        }
    }
}
