<?php

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

class Aysa_Seo_Generation_Processor {
    
    private $api_base_url;
    private $auth_token;
    
    public function __construct() {
        $this->api_base_url = defined('AYSA_API_BASE_URL') ? AYSA_API_BASE_URL : 'https://api.aysa.ai/';
        $this->auth_token = get_option('aysa_auth_token', '');
    }
    
    /**
     * Process SEO generation job
     * 
     * @param array $job_data Job data containing entity information
     * @return array|WP_Error Processing result
     */
    public function process($job_data) {
        try {
            // Validate job data
            if (empty($job_data['entity_id']) || empty($job_data['entity_type']) || empty($job_data['keyword'])) {
                return new WP_Error('invalid_job_data', 'Missing required job data: entity_id, entity_type, or keyword');
            }
            
            $entity_id = intval($job_data['entity_id']);
            $entity_type = sanitize_text_field($job_data['entity_type']);
            $keyword = sanitize_text_field($job_data['keyword']);
            $project_id = isset($job_data['project_id']) ? intval($job_data['project_id']) : 0;
            
            // Log the start of processing
            aysa_debug_log("AYSA SEO Generation: Starting processing for entity ID {$entity_id}, type {$entity_type}, keyword '{$keyword}'");
            
            // Generate SEO content using the same logic as manual generation
            $seo_result = $this->generate_seo_content($entity_id, $entity_type, $keyword, $project_id);
            
            if (is_wp_error($seo_result)) {
                aysa_debug_log("AYSA SEO Generation: Error generating SEO content: " . $seo_result->get_error_message());
                return $seo_result;
            }
            
            // Add to pending reviews for approval
            $review_result = $this->add_to_pending_reviews($entity_id, $entity_type, $keyword, $seo_result, $project_id);
            
            if (is_wp_error($review_result)) {
                aysa_debug_log("AYSA SEO Generation: Error adding to pending reviews: " . $review_result->get_error_message());
                return $review_result;
            }
            
            // Log successful completion
            aysa_debug_log("AYSA SEO Generation: Successfully processed entity ID {$entity_id} and added to pending reviews");
            
            return array(
                'success' => true,
                'entity_id' => $entity_id,
                'entity_type' => $entity_type,
                'keyword' => $keyword,
                'seo_result' => $seo_result,
                'review_id' => $review_result['review_id'],
                'message' => 'SEO content generated and added to pending reviews'
            );
            
        } catch (Exception $e) {
            aysa_debug_log("AYSA SEO Generation: Exception during processing: " . $e->getMessage());
            return new WP_Error('processing_exception', 'Exception during SEO generation: ' . $e->getMessage());
        }
    }
    
    /**
     * Generate SEO content for an entity
     * 
     * @param int $entity_id Entity ID
     * @param string $entity_type Entity type (Product, Category, Page, Post)
     * @param string $keyword Primary keyword
     * @param int $project_id Project ID
     * @return array|WP_Error SEO generation result
     */
    private function generate_seo_content($entity_id, $entity_type, $keyword, $project_id) {
        try {
            // Get entity information
            $entity_info = $this->get_entity_info($entity_id, $entity_type);
            if (is_wp_error($entity_info)) {
                return $entity_info;
            }
            
            // Get SEO settings with entity context
             $seo_settings = $this->get_seo_settings($project_id, $entity_id, $entity_type);
            
            // Prepare API calls based on entity type
            $api_calls = $this->prepare_api_calls($entity_type, $keyword, $seo_settings, $project_id);
            
            // Execute API calls
            $api_results = $this->execute_api_calls($api_calls);
            
            if (is_wp_error($api_results)) {
                return $api_results;
            }
            
            // Process and format results
            $processed_results = $this->process_api_results($api_results, $entity_type);
            
            return $processed_results;
            
        } catch (Exception $e) {
            return new WP_Error('generation_exception', 'Exception during SEO generation: ' . $e->getMessage());
        }
    }
    
    /**
     * Get entity information
     * 
     * @param int $entity_id Entity ID
     * @param string $entity_type Entity type
     * @return array|WP_Error Entity information
     */
    private function get_entity_info($entity_id, $entity_type) {
        switch ($entity_type) {
            case 'Product':
                $product = get_post($entity_id);
                if (!$product || $product->post_type !== 'product') {
                    return new WP_Error('invalid_product', 'Product not found');
                }
                return array(
                    'id' => $entity_id,
                    'type' => 'Product',
                    'title' => $product->post_title,
                    'content' => $product->post_content,
                    'excerpt' => $product->post_excerpt,
                    'url' => get_permalink($entity_id)
                );
                
            case 'Category':
                $term = get_term($entity_id);
                if (!$term || is_wp_error($term)) {
                    return new WP_Error('invalid_category', 'Category not found');
                }
                return array(
                    'id' => $entity_id,
                    'type' => 'Category',
                    'title' => $term->name,
                    'description' => $term->description,
                    'url' => get_term_link($term)
                );
                
            case 'Page':
            case 'Post':
                $post = get_post($entity_id);
                if (!$post) {
                    return new WP_Error('invalid_post', 'Post/Page not found');
                }
                return array(
                    'id' => $entity_id,
                    'type' => $entity_type,
                    'title' => $post->post_title,
                    'content' => $post->post_content,
                    'excerpt' => $post->post_excerpt,
                    'url' => get_permalink($entity_id)
                );
                
            default:
                return new WP_Error('invalid_entity_type', 'Invalid entity type: ' . $entity_type);
        }
    }
    
    /**
     * Get SEO settings for the project
     * 
     * @param int $project_id Project ID
     * @param int $entity_id Entity ID (optional)
     * @param string $entity_type Entity type (optional)
     * @return array SEO settings
     */
    private function get_seo_settings($project_id, $entity_id = null, $entity_type = null) {
        // Detect language using multiple sources with entity context
        $detected_language = $this->detect_language($entity_id, $entity_type);
        
        // Default settings with detected language
        $default_settings = array(
            'language' => $detected_language,
            'tone' => 'professional',
            'target_audience' => 'general',
            'search_intent' => 'informational'
        );
        
        // If we have a project ID, try to get specific settings from API
        if ($project_id > 0) {
            $api_settings = $this->fetch_project_seo_settings($project_id);
            if ($api_settings && is_array($api_settings)) {
                // Merge API settings with defaults, prioritizing API values
                $default_settings = array_merge($default_settings, $api_settings);
            }
        }
        
        aysa_debug_log("AYSA SEO Generation: Using language '{$default_settings['language']}' for project {$project_id}");
        
        return $default_settings;
    }
    
    /**
     * Detect language from multiple sources with priority order
     * 
     * @param int $entity_id Entity ID (optional)
     * @param string $entity_type Entity type (optional)
     * @return string Detected language code
     */
    private function detect_language($entity_id = null, $entity_type = null) {
        // Priority 1: Association language from metabox (highest priority)
        if ($entity_id && $entity_type) {
            $association_language = $this->get_association_language($entity_id, $entity_type);
            if (!empty($association_language)) {
                aysa_debug_log("AYSA SEO Generation: Using association language from metabox: {$association_language}");
                return $association_language;
            }
        }
        
        // Priority 2: Context-specific language via Aysa_Media class
        if (class_exists('Aysa_Media')) {
            $aysa_media = new Aysa_Media();
            if (method_exists($aysa_media, 'get_context_language_optimize')) {
                $context_language = $aysa_media->get_context_language_optimize();
                if (!empty($context_language)) {
                    $language_code = $this->convert_language_name_to_code($context_language);
                    aysa_debug_log("AYSA SEO Generation: Using context language: {$language_code}");
                    return $language_code;
                }
            }
        }
        
        // Priority 3: Project-specific language from API
        $project_id = $this->get_project_id();
        if ($project_id) {
            $project_language = $this->get_project_language($project_id);
            if (!empty($project_language)) {
                $language_code = $this->convert_language_name_to_code($project_language);
                aysa_debug_log("AYSA SEO Generation: Using project language: {$language_code}");
                return $language_code;
            }
        }
        
        // Priority 4: WordPress locale
        $wp_locale = get_locale();
        if ($wp_locale) {
            // Convert WordPress locale to language code (e.g., 'en_US' -> 'en', 'ro_RO' -> 'ro')
            $language_code = substr($wp_locale, 0, 2);
            aysa_debug_log("AYSA SEO Generation: Using WordPress locale language: {$language_code} (from {$wp_locale})");
            return $language_code;
        }
        
        // Priority 5: Global AYSA settings via Aysa_Media class
        if (class_exists('Aysa_Media')) {
            $media_instance = new Aysa_Media();
            if (method_exists($media_instance, 'get_global_language_optimize')) {
                $global_language = $media_instance->get_global_language_optimize();
                if ($global_language) {
                    // Convert full language name to code if needed
                    $language_code = $this->convert_language_name_to_code($global_language);
                    aysa_debug_log("AYSA SEO Generation: Using global language from media class: {$language_code}");
                    return $language_code;
                }
            }
        }
        
        // Priority 6: English fallback
        aysa_debug_log("AYSA SEO Generation: Using fallback language: en");
        return 'en';
    }
    
    /**
     * Get project ID from current context
     * 
     * @return int|null Project ID or null if not found
     */
    private function get_project_id() {
        // Try to get project ID from various sources
        
        // Check if it's set in the current request
        if (isset($_REQUEST['project_id'])) {
            return intval($_REQUEST['project_id']);
        }
        
        // Check global option
        $project_id = get_option('aysa_current_project_id', 0);
        if ($project_id > 0) {
            return $project_id;
        }
        
        // Check if Aysa_Media class has project context
        if (class_exists('Aysa_Media')) {
            $aysa_media = new Aysa_Media();
            if (method_exists($aysa_media, 'get_current_project_id')) {
                $project_id = $aysa_media->get_current_project_id();
                if ($project_id > 0) {
                    return $project_id;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Get project language from API
     * 
     * @param int $project_id Project ID
     * @return string|null Language code or null if not found
     */
    private function get_project_language($project_id) {
        $cache_key = 'aysa_project_language_' . $project_id;
        $cached_language = get_transient($cache_key);
        
        if ($cached_language !== false) {
            return $cached_language;
        }
        
        $api_url = $this->api_base_url . 'api/SeoSettings/ByProject/' . $project_id;
        
        $response = wp_remote_get($api_url, array(
            'timeout' => 15,
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->auth_token,
                'Content-Type' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            aysa_debug_log('AYSA SEO Generation: Error fetching project language: ' . $response->get_error_message());
            return null;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            aysa_debug_log('AYSA SEO Generation: API returned status code: ' . $response_code);
            return null;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
            aysa_debug_log('AYSA SEO Generation: Invalid JSON response: ' . json_last_error_msg());
            return null;
        }
        
        $language = null;
        if (isset($data['languageOptimize'])) {
            $language = $this->convert_language_name_to_code($data['languageOptimize']);
        } elseif (isset($data['primaryLanguage'])) {
            $language = $this->convert_language_name_to_code($data['primaryLanguage']);
        }
        
        if ($language) {
            // Cache for 10 minutes to reduce API calls
            set_transient($cache_key, $language, 10 * MINUTE_IN_SECONDS);
        }
        
        return $language;
    }
    
    /**
     * Fetch complete project SEO settings from API
     * 
     * @param int $project_id Project ID
     * @return array|null SEO settings or null if not found
     */
    private function fetch_project_seo_settings($project_id) {
        $cache_key = 'aysa_project_seo_settings_' . $project_id;
        $cached_settings = get_transient($cache_key);
        
        if ($cached_settings !== false) {
            return $cached_settings;
        }
        
        $api_url = $this->api_base_url . 'api/SeoSettings/ByProject/' . $project_id;
        
        $response = wp_remote_get($api_url, array(
            'timeout' => 15,
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->auth_token,
                'Content-Type' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            return null;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return null;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
            return null;
        }
        
        // Map API response to our settings format
        $settings = array();
        
        if (isset($data['languageOptimize'])) {
            $settings['language'] = $this->convert_language_name_to_code($data['languageOptimize']);
        } elseif (isset($data['primaryLanguage'])) {
            $settings['language'] = $this->convert_language_name_to_code($data['primaryLanguage']);
        }
        
        if (isset($data['targetedCity'])) {
            $settings['targetedCity'] = $data['targetedCity'];
        }
        
        if (isset($data['targetedCountry'])) {
            $settings['targetedCountry'] = $data['targetedCountry'];
        }
        
        if (isset($data['targetedSearchEngine'])) {
            $settings['targetedSearchEngine'] = $data['targetedSearchEngine'];
        }
        
        if (isset($data['brandName'])) {
            $settings['brandName'] = $data['brandName'];
        }
        
        if (isset($data['updateFrequency'])) {
            $settings['updateFrequency'] = $data['updateFrequency'];
        }
        
        // Cache for 10 minutes
        if (!empty($settings)) {
            set_transient($cache_key, $settings, 10 * MINUTE_IN_SECONDS);
        }
        
        return $settings;
    }
    
    /**
     * Convert language name to language code
     * 
     * @param string $language_name Language name (e.g., 'English', 'Romanian')
     * @return string Language code (e.g., 'en', 'ro')
     */
    private function convert_language_name_to_code($language_name) {
        if (empty($language_name)) {
            return 'en';
        }
        
        // If it's already a code (2 characters), return as is
        if (strlen($language_name) === 2) {
            return strtolower($language_name);
        }
        
        // Language name to code mapping
        $language_map = array(
            'english' => 'en',
            'romanian' => 'ro',
            'french' => 'fr',
            'german' => 'de',
            'spanish' => 'es',
            'italian' => 'it',
            'portuguese' => 'pt',
            'dutch' => 'nl',
            'polish' => 'pl',
            'czech' => 'cs',
            'hungarian' => 'hu',
            'bulgarian' => 'bg',
            'croatian' => 'hr',
            'slovak' => 'sk',
            'slovenian' => 'sl',
            'serbian' => 'sr',
            'russian' => 'ru',
            'ukrainian' => 'uk',
            'greek' => 'el',
            'turkish' => 'tr',
            'arabic' => 'ar',
            'hebrew' => 'he',
            'chinese' => 'zh',
            'japanese' => 'ja',
            'korean' => 'ko',
            'thai' => 'th',
            'vietnamese' => 'vi',
            'hindi' => 'hi',
            'bengali' => 'bn',
            'urdu' => 'ur',
            'persian' => 'fa',
            'swedish' => 'sv',
            'norwegian' => 'no',
            'danish' => 'da',
            'finnish' => 'fi'
        );
        
        $language_lower = strtolower(trim($language_name));
        
        if (isset($language_map[$language_lower])) {
            return $language_map[$language_lower];
        }
        
        // If no mapping found, try to extract first 2 characters
        return substr($language_lower, 0, 2);
    }
    
    /**
     * Get association language from metabox settings
     * 
     * @param int $entity_id Entity ID
     * @param string $entity_type Entity type
     * @return string|null Language code or null if not found
     */
    private function get_association_language($entity_id, $entity_type) {
        switch ($entity_type) {
            case 'Product':
            case 'product':
                // For products, check post meta
                $language = get_post_meta($entity_id, 'aysa_language_optimize', true);
                if (!empty($language)) {
                    return $this->convert_language_name_to_code($language);
                }
                break;
                
            case 'Category':
            case 'category':
                // For categories, check term meta
                $seo_settings = get_term_meta($entity_id, 'aysa_seo_settings', true);
                if (is_array($seo_settings) && isset($seo_settings['language_optimize'])) {
                    return $this->convert_language_name_to_code($seo_settings['language_optimize']);
                }
                break;
                
            case 'Page':
            case 'Post':
            case 'page':
            case 'post':
                // For pages/posts, check post meta
                $language = get_post_meta($entity_id, 'aysa_language_optimize', true);
                if (!empty($language)) {
                    return $this->convert_language_name_to_code($language);
                }
                break;
        }
        
        return null;
    }
    
    /**
     * Prepare API calls based on entity type
     * 
     * @param string $entity_type Entity type
     * @param string $keyword Primary keyword
     * @param array $seo_settings SEO settings
     * @return array API calls to make
     */
    private function prepare_api_calls($entity_type, $keyword, $seo_settings, $project_id) {
        $api_calls = array();
        
        // Common API calls for all entity types
        $api_calls[] = array(
            'type' => 'meta-title',
            'keyword' => $keyword,
            'language' => $seo_settings['language'],
            'entity_type' => $entity_type,
            'seo_settings' => $seo_settings,
            'project_id' => $project_id
        );
        
        $api_calls[] = array(
            'type' => 'meta-description',
            'keyword' => $keyword,
            'language' => $seo_settings['language'],
            'entity_type' => $entity_type,
            'seo_settings' => $seo_settings,
            'project_id' => $project_id
        );
        
        $api_calls[] = array(
            'type' => 'meta-keywords',
            'keyword' => $keyword,
            'language' => $seo_settings['language'],
            'entity_type' => $entity_type,
            'seo_settings' => $seo_settings,
            'project_id' => $project_id
        );
        
        $api_calls[] = array(
            'type' => 'second-keyword',
            'keyword' => $keyword,
            'language' => $seo_settings['language'],
            'entity_type' => $entity_type,
            'seo_settings' => $seo_settings,
            'project_id' => $project_id
        );
        
        // Entity-specific API calls
        switch ($entity_type) {
            case 'Product':
                $api_calls[] = array(
                    'type' => 'product-or-category-title',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'product',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                
                $api_calls[] = array(
                    'type' => 'seo-optimized-content',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'product',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                
                $api_calls[] = array(
                    'type' => 'product-short-description',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'product',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                
                $api_calls[] = array(
                    'type' => 'product-permalink',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'product',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                break;
                
            case 'Category':
                $api_calls[] = array(
                    'type' => 'product-or-category-title',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'category',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                
                $api_calls[] = array(
                    'type' => 'seo-optimized-content',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'category',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                
                $api_calls[] = array(
                    'type' => 'category-permalink',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => 'category',
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                break;
                
            case 'Page':
            case 'Post':
                $api_calls[] = array(
                    'type' => 'seo-optimized-content',
                    'keyword' => $keyword,
                    'language' => $seo_settings['language'],
                    'entity_type' => strtolower($entity_type),
                    'seo_settings' => $seo_settings,
                    'project_id' => $project_id
                );
                break;
        }
        
        return $api_calls;
    }
    
    /**
     * Execute API calls
     * 
     * @param array $api_calls Array of API calls to make
     * @return array|WP_Error API results
     */
    private function execute_api_calls($api_calls) {
        $results = array();
        $errors = array();
        
        foreach ($api_calls as $call) {
            $result = $this->make_api_call($call);
            
            if (is_wp_error($result)) {
                $errors[] = array(
                    'type' => $call['type'],
                    'error' => $result->get_error_message()
                );
                // Continue with other calls even if one fails
                $results[$call['type']] = '';
            } else {
                $results[$call['type']] = $result;
            }
        }
        
        // If all calls failed, return error
        if (count($errors) === count($api_calls)) {
            return new WP_Error('all_api_calls_failed', 'All API calls failed: ' . json_encode($errors));
        }
        
        return $results;
    }
    
    /**
     * Make a single API call with improved timeout and retry logic
     * 
     * @param array $call API call data
     * @return string|WP_Error API response
     */
    private function make_api_call($call) {
        $type = $call['type'];
        $keyword = $call['keyword'];
        $language = $call['language'];
        $entity_type = $call['entity_type'];
        $seo_settings = $call['seo_settings'] ?? array();
        $project_id = $call['project_id'] ?? 0;
        
        // Build API URL based on call type
        $url = $this->build_api_url($type, $keyword, $language, $entity_type);
        
        if (is_wp_error($url)) {
            return $url;
        }
        
        // Build POST data if needed
        $post_data = $this->build_post_data($type, $keyword, $language, $entity_type, $seo_settings, $project_id);
        
        // Determine timeout based on API type
        $timeout = $this->get_timeout_for_api_type($type);
        $max_retries = $this->get_max_retries_for_api_type($type);
        
        aysa_debug_log("AYSA SEO Generation: Making API call for {$type} with timeout {$timeout}s, max retries {$max_retries}");
        
        // Try the API call with retries
        for ($attempt = 1; $attempt <= $max_retries; $attempt++) {
            try {
                $result = $this->execute_single_api_call($url, $timeout, $attempt, $post_data);
                
                if (!is_wp_error($result)) {
                    aysa_debug_log("AYSA SEO Generation: API call for {$type} succeeded on attempt {$attempt}");
                    return $result;
                }
                
                // If it's the last attempt, return the error
                if ($attempt === $max_retries) {
                    aysa_debug_log("AYSA SEO Generation: API call for {$type} failed after {$max_retries} attempts: " . $result->get_error_message());
                    return $result;
                }
                
                // Wait before retry (exponential backoff)
                $wait_time = pow(2, $attempt - 1) * 5; // 5s, 10s, 20s, etc.
                aysa_debug_log("AYSA SEO Generation: API call for {$type} failed on attempt {$attempt}, waiting {$wait_time}s before retry");
                sleep($wait_time);
                
            } catch (Exception $e) {
                aysa_debug_log("AYSA SEO Generation: Exception during API call for {$type} on attempt {$attempt}: " . $e->getMessage());
                
                if ($attempt === $max_retries) {
                    return new WP_Error('api_exception', 'Exception during API call: ' . $e->getMessage());
                }
            }
        }
        
        return new WP_Error('api_max_retries_exceeded', "API call for {$type} failed after {$max_retries} attempts");
    }
    
    /**
     * Execute a single API call with proper timeout handling
     * 
     * @param string $url API URL
     * @param int $timeout Timeout in seconds
     * @param int $attempt Current attempt number
     * @return string|WP_Error API response
     */
    private function execute_single_api_call($url, $timeout, $attempt, $post_data = null) {
        // Set up request arguments with proper timeout
        $args = array(
            'timeout' => $timeout,
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->auth_token,
                'Content-Type' => 'application/json',
                'User-Agent' => 'AYSA-WordPress-Plugin/1.0'
            ),
            'sslverify' => false, // For development environments
            'blocking' => true, // Ensure we wait for response
            'httpversion' => '1.1'
        );
        
        // If we have POST data, use POST method
        if ($post_data !== null) {
            $args['method'] = 'POST';
            $args['body'] = json_encode($post_data);
        } else {
            $args['method'] = 'GET';
        }
        
        aysa_debug_log("AYSA SEO Generation: Making API request to {$url} with {$timeout}s timeout (attempt {$attempt})");
        
        // Make the API request
        $response = wp_remote_request($url, $args);
        
        // Log response details
        if (is_wp_error($response)) {
            aysa_debug_log("AYSA SEO Generation: API request failed: " . $response->get_error_message());
        } else {
            $status_code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            aysa_debug_log("AYSA SEO Generation: API response - Status: {$status_code}, Body length: " . strlen($body));
            aysa_debug_log("AYSA SEO Generation: API response body: " . substr($body, 0, 500) . "...");
        }
        
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            
            // Check if it's a timeout error
            if (strpos($error_message, 'timeout') !== false || strpos($error_message, 'cURL error 28') !== false) {
                return new WP_Error('api_timeout', "API request timed out after {$timeout} seconds");
            }
            
            return new WP_Error('api_request_failed', 'API request failed: ' . $error_message);
        }
        
        $body = wp_remote_retrieve_body($response);
        $status_code = wp_remote_retrieve_response_code($response);
        $response_headers = wp_remote_retrieve_headers($response);
        
        aysa_debug_log("AYSA SEO Generation: API response received - Status: {$status_code}, Body length: " . strlen($body));
        
        // Check for successful response
        if ($status_code !== 200) {
            return new WP_Error('api_error', "API returned status {$status_code}: {$body}");
        }
        
        // Check if response is empty
        if (empty($body)) {
            return new WP_Error('api_empty_response', 'API returned empty response');
        }
        
        // Try to parse as JSON first, but handle plain text responses
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            // If JSON parsing fails, treat as plain text
            aysa_debug_log("AYSA SEO Generation: JSON parse failed, treating as plain text: " . json_last_error_msg());
            $data = $body; // Use raw body as data
        }
        
        // Extract content based on API type
        $extracted_content = $this->extract_content_from_response($this->get_api_type_from_url($url), $data);
        
        if (empty($extracted_content)) {
            return new WP_Error('api_empty_content', 'No content extracted from API response');
        }
        
        return $extracted_content;
    }
    
    /**
     * Get appropriate timeout for API type
     * 
     * @param string $type API call type
     * @return int Timeout in seconds
     */
    private function get_timeout_for_api_type($type) {
        switch ($type) {
            case 'seo-optimized-content':
                return 180; // 3 minutes for content generation
                
            case 'second-keyword':
                return 120; // 2 minutes for keyword analysis
                
            case 'product-or-category-title':
            case 'product-short-description':
                return 90; // 1.5 minutes for title generation
                
            case 'meta-title':
            case 'meta-description':
            case 'meta-keywords':
            case 'product-permalink':
            case 'category-permalink':
                return 60; // 1 minute for meta generation
                
            default:
                return 120; // Default 2 minutes
        }
    }
    
    /**
     * Get maximum retries for API type
     * 
     * @param string $type API call type
     * @return int Maximum number of retries
     */
    private function get_max_retries_for_api_type($type) {
        switch ($type) {
            case 'seo-optimized-content':
                return 2; // Content generation is expensive, fewer retries
                
            case 'second-keyword':
                return 3; // Keyword analysis can be retried more
                
            default:
                return 3; // Default 3 retries
        }
    }
    
    /**
     * Extract API type from URL for content extraction
     * 
     * @param string $url API URL
     * @return string API type
     */
    private function get_api_type_from_url($url) {
        if (strpos($url, 'seo-meta-title') !== false) return 'meta-title';
        if (strpos($url, 'seo-meta-description') !== false) return 'meta-description';
        if (strpos($url, 'seo-meta-keywords') !== false) return 'meta-keywords';
        if (strpos($url, 'keywords-for-keywords-for-plugin') !== false) return 'second-keyword';
        if (strpos($url, 'product-or-category-title') !== false) return 'product-or-category-title';
        if (strpos($url, 'seo-optimized-content') !== false) return 'seo-optimized-content';
        if (strpos($url, 'product-short-description') !== false) return 'product-short-description';
        if (strpos($url, 'seo-friendly-url') !== false) {
            if (strpos($url, 'page_type=product') !== false) return 'product-permalink';
            if (strpos($url, 'page_type=category') !== false) return 'category-permalink';
        }
        
        return 'unknown';
    }
    
    /**
     * Build API URL for a specific call type
     * 
     * @param string $type API call type
     * @param string $keyword Keyword
     * @param string $language Language
     * @param string $entity_type Entity type
     * @return string|WP_Error API URL
     */
    private function build_api_url($type, $keyword, $language, $entity_type) {
        if (empty($this->api_base_url)) {
            return new WP_Error('no_api_base_url', 'API base URL not configured');
        }
        
        $base_url = rtrim($this->api_base_url, '/');
        
        switch ($type) {
            case 'meta-title':
                return $base_url . '/api/chatgpt/seo-meta-title';
                
            case 'meta-description':
                return $base_url . '/api/chatgpt/seo-meta-description';
                
            case 'meta-keywords':
                return $base_url . '/api/chatgpt/seo-meta-keywords';
                
            case 'second-keyword':
                return $base_url . '/api/SEO/keywords-for-keywords-for-plugin?keyword=' . urlencode($keyword) . '&locationName=Romania';
                
            case 'product-or-category-title':
                return $base_url . '/api/chatgpt/product-or-category-title?target_keyword=' . urlencode($keyword) . '&language=' . urlencode($language) . '&page_type=' . urlencode($entity_type);
                
            case 'seo-optimized-content':
                return $base_url . '/api/chatgpt/seo-optimized-content';
                
            case 'product-short-description':
                return $base_url . '/api/chatgpt/product-short-description?keyword=' . urlencode($keyword) . '&language=' . urlencode($language);
                
            case 'product-permalink':
                return $base_url . '/api/chatgpt/seo-friendly-url?target_keyword=' . urlencode($keyword) . '&language=' . urlencode($language) . '&page_type=product';
                
            case 'category-permalink':
                return $base_url . '/api/chatgpt/seo-friendly-url?target_keyword=' . urlencode($keyword) . '&language=' . urlencode($language) . '&page_type=category';
                
            default:
                return new WP_Error('unknown_api_type', 'Unknown API call type: ' . $type);
        }
    }
    
    /**
     * Build POST data for API calls that require it
     * 
     * @param string $type API call type
     * @param string $keyword Primary keyword
     * @param string $language Language
     * @param string $entity_type Entity type
     * @param array $seo_settings SEO settings
     * @param int $project_id Project ID
     * @return array|null POST data or null for GET requests
     */
    private function build_post_data($type, $keyword, $language, $entity_type, $seo_settings, $project_id) {
        switch ($type) {
            case 'meta-title':
                return array(
                    'language' => $language,
                    'pageType' => $entity_type,
                    'domain' => get_site_url(),
                    'primaryKeyword' => $keyword,
                    'secondaryKeywords' => array(),
                    'relatedKeywords' => array(),
                    'targetAudience' => $seo_settings['targetedSearchEngine'] ?? '',
                    'searchIntent' => $seo_settings['updateFrequency'] ?? '',
                    'city' => $seo_settings['targetedCity'] ?? '',
                    'brandName' => $seo_settings['brandName'] ?? '',
                    'projectId' => $project_id
                );
                
            case 'meta-description':
                return array(
                    'language' => $language,
                    'pageType' => $entity_type,
                    'domain' => get_site_url(),
                    'primaryKeyword' => $keyword,
                    'secondaryKeywords' => array(),
                    'relatedKeywords' => array(),
                    'targetAudience' => $seo_settings['targetedSearchEngine'] ?? '',
                    'searchIntent' => $seo_settings['updateFrequency'] ?? '',
                    'city' => $seo_settings['targetedCity'] ?? '',
                    'brandName' => $seo_settings['brandName'] ?? '',
                    'projectId' => $project_id
                );
                
            case 'meta-keywords':
                return array(
                    'language' => $language,
                    'pageType' => $entity_type,
                    'domain' => get_site_url(),
                    'primaryKeyword' => $keyword,
                    'secondaryKeywords' => array(),
                    'relatedKeywords' => array(),
                    'projectId' => $project_id
                );
                
            case 'seo-optimized-content':
                return array(
                    'language' => $language,
                    'pageType' => $entity_type,
                    'domain' => get_site_url(),
                    'primaryKeyword' => $keyword,
                    'secondaryKeywords' => array(),
                    'relatedKeywords' => array(),
                    'minimumWordCount' => 300,
                    'documentOutline' => array(),
                    'includeTldr' => false,
                    'numberOfImages' => 0,
                    'city' => $seo_settings['targetedCity'] ?? '',
                    'paymentMethods' => array(),
                    'deliveryMethods' => array(),
                    'tone' => 'professional',
                    'targetAudience' => $seo_settings['targetedSearchEngine'] ?? '',
                    'searchIntent' => $seo_settings['updateFrequency'] ?? '',
                    'existingPageContent' => false,
                    'pageUrl' => '',
                    'websiteContext' => '',
                    'brandName' => $seo_settings['brandName'] ?? '',
                    'includeFaq' => true,
                    'includeFaqSchema' => false,
                    'competitorUrls' => array(),
                    'projectId' => $project_id
                );
                
            default:
                return null; // GET request
        }
    }
    
    /**
     * Extract content from API response
     * 
     * @param string $type API call type
     * @param array $data API response data
     * @return string Extracted content
     */
    private function extract_content_from_response($type, $data) {
        switch ($type) {
            case 'second-keyword':
                if (isset($data['tasks']) && is_array($data['tasks']) && !empty($data['tasks'])) {
                    $task = $data['tasks'][0];
                    if (isset($task['result']) && is_array($task['result'])) {
                        $keywords = array();
                        foreach ($task['result'] as $item) {
                            if (isset($item['keyword'])) {
                                $keywords[] = $item['keyword'];
                            }
                        }
                        return implode(', ', array_slice($keywords, 0, 20));
                    }
                }
                return '';
                
            case 'product-permalink':
            case 'category-permalink':
                if (isset($data['seoFriendlyUrl'])) {
                    return $data['seoFriendlyUrl'];
                }
                return '';
                
            default:
                // For most API calls, return the content directly
                if (isset($data['content'])) {
                    return $data['content'];
                }
                if (isset($data['suggestion'])) {
                    return $data['suggestion'];
                }
                if (is_string($data)) {
                    return $data;
                }
                return '';
        }
    }
    
    /**
     * Process API results into final format
     * 
     * @param array $api_results Raw API results
     * @param string $entity_type Entity type
     * @return array Processed results
     */
    private function process_api_results($api_results, $entity_type) {
        $processed = array();
        
        // Map API results to final format
        $processed['metaTitle'] = $api_results['meta-title'] ?? '';
        $processed['metaDescription'] = $api_results['meta-description'] ?? '';
        $processed['metaKeywords'] = $api_results['meta-keywords'] ?? '';
        $processed['secondKeyword'] = $api_results['second-keyword'] ?? '';
        
        switch ($entity_type) {
            case 'Product':
                $processed['entityTitle'] = $api_results['product-or-category-title'] ?? '';
                $processed['entityContent'] = $api_results['seo-optimized-content'] ?? '';
                $processed['shortProductDescription'] = $api_results['product-short-description'] ?? '';
                $processed['permalink'] = $api_results['product-permalink'] ?? '';
                break;
                
            case 'Category':
                $processed['entityTitle'] = $api_results['product-or-category-title'] ?? '';
                $processed['entityContent'] = $api_results['seo-optimized-content'] ?? '';
                $processed['permalink'] = $api_results['category-permalink'] ?? '';
                break;
                
            case 'Page':
            case 'Post':
                $processed['entityContent'] = $api_results['seo-optimized-content'] ?? '';
                break;
        }
        
        return $processed;
    }
    
    /**
     * Add generated SEO content to pending reviews
     * 
     * @param int $entity_id Entity ID
     * @param string $entity_type Entity type
     * @param string $keyword Keyword
     * @param array $seo_result SEO generation result
     * @param int $project_id Project ID
     * @return array|WP_Error Review result
     */
    private function add_to_pending_reviews($entity_id, $entity_type, $keyword, $seo_result, $project_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'aysa_automated_pending_reviews';
        
        // Check if table exists, if not create it
        $this->create_pending_reviews_table();
        
        // Extract main keyword from serialized data if needed
        $clean_keyword = $this->extract_main_keyword($keyword);
        
        // Log the SEO result before inserting
        aysa_debug_log("AYSA SEO Generation: Final SEO result for entity {$entity_id}: " . json_encode($seo_result));
        aysa_debug_log("AYSA DUPLICATE DEBUG: Adding to pending reviews table - Entity ID: {$entity_id}, Type: {$entity_type}, Original Keyword Length: " . strlen($keyword) . ", Clean Keyword: {$clean_keyword}");
        
        // Insert the review
        $result = $wpdb->insert(
            $table_name,
            array(
                'entity_id' => $entity_id,
                'entity_type' => $entity_type,
                'keyword' => $clean_keyword,
                'seo_data' => wp_json_encode($seo_result),
                'project_id' => $project_id,
                'status' => 'pending',
                'created_at' => current_time('mysql'),
                'source' => 'automated_seo_generation'
            ),
            array('%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s')
        );
        
        if ($result === false) {
            return new WP_Error('db_error', 'Failed to add to pending reviews: ' . $wpdb->last_error);
        }
        
        $review_id = $wpdb->insert_id;
        
        return array(
            'review_id' => $review_id,
            'success' => true
        );
    }
    
    /**
     * Extract main keyword from serialized data or return as-is if it's already clean
     * 
     * @param string $keyword Original keyword (may be serialized data)
     * @return string Clean keyword (max 255 chars)
     */
    private function extract_main_keyword($keyword) {
        // If keyword is not too long, return as-is
        if (strlen($keyword) <= 255 && strpos($keyword, 'a:') !== 0) {
            return $keyword;
        }
        
        // Try to unserialize if it looks like serialized data
        if (strpos($keyword, 'a:') === 0) {
            $unserialized = @unserialize($keyword);
            if (is_array($unserialized)) {
                // Extract the main keyword
                if (isset($unserialized['keyword'])) {
                    $main_keyword = $unserialized['keyword'];
                    // Limit to 255 characters and return
                    return substr($main_keyword, 0, 255);
                }
            }
        }
        
        // If all else fails, truncate to 255 characters
        return substr($keyword, 0, 255);
    }
    
    /**
     * Create pending reviews table if it doesn't exist
     */
    private function create_pending_reviews_table() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'aysa_automated_pending_reviews';
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            entity_id bigint(20) unsigned NOT NULL,
            entity_type varchar(50) NOT NULL,
            keyword varchar(255) NOT NULL,
            seo_data longtext NOT NULL,
            project_id bigint(20) unsigned DEFAULT 0,
            status varchar(20) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            reviewed_at datetime NULL,
            reviewed_by bigint(20) unsigned NULL,
            source varchar(50) DEFAULT 'automated_seo_generation',
            PRIMARY KEY (id),
            KEY entity_id (entity_id),
            KEY entity_type (entity_type),
            KEY status (status),
            KEY created_at (created_at)
        ) {$charset_collate};";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}
