<?php
/**
 * EONSR AEO Agent - WP Cron Background Polling for Auto-Translate
 *
 * Implements a background worker to check translation job status,
 * retrieve content from Node.js, and create WordPress posts.
 *
 * Workflow:
 * 1. User publishes -> Queue job -> Return immediately.
 * 2. WP Cron runs every minute -> Checks pending jobs.
 * 3. Job completed -> Create WP post -> Reuse media from source -> Publish.
 *
 * @package EONSR_AEO_Agent
 */

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

/* ==========================================================================
   SECTION 1: CRON SCHEDULING
   ========================================================================== */

/**
 * Schedule the translation poller event.
 */
function eonsr_aeo_agent_schedule_translation_poller()
{
    if (!wp_next_scheduled('eonsr_aeo_agent_poll_translation_jobs')) {
        wp_schedule_event(time(), 'every_minute', 'eonsr_aeo_agent_poll_translation_jobs');
    }
}
add_action('wp', 'eonsr_aeo_agent_schedule_translation_poller');

/**
 * Add custom cron interval (Every Minute).
 */
add_filter('cron_schedules', function ($schedules) {
    $schedules['every_minute'] = [
        'interval' => 60,
        // FIX: Added Text Domain 'eonsr-aeo-agent' as the second argument
        'display'  => __('Every Minute', 'eonsr-aeo-agent')
    ];
    return $schedules;
});

/* ==========================================================================
   SECTION 2: MAIN WORKER (JOB POLLING)
   ========================================================================== */

/**
 * Main worker to poll translation jobs status and create posts.
 */
add_action('eonsr_aeo_agent_poll_translation_jobs', function () {
    // 1. Load Logic Handler
    if (!function_exists('eonsr_aeo_agent_handle_post_creation_logic')) {
        // Updated Path with prefix if logic file name changed, assuming path is correct based on previous files
        $rest_file = plugin_dir_path(__FILE__) . 'includes/rest-api-sync.php';
        if (file_exists($rest_file)) {
            require_once $rest_file;
        }
    }

    // 2. Fetch Posts with Pending Jobs
    $posts_with_jobs = get_posts([
        'post_type'      => 'post',
        'post_status'    => 'any',
        'meta_key'       => '_eonsr_aeo_translation_jobs', // Updated Meta Key
        'posts_per_page' => 10,
        'fields'         => 'ids'
    ]);

    if (empty($posts_with_jobs)) {
        return;
    }

    // 3. Process Each Source Post
    foreach ($posts_with_jobs as $source_post_id) {
        // Updated Meta Key
        $translation_jobs = get_post_meta($source_post_id, '_eonsr_aeo_translation_jobs', true);
        
        if (!is_array($translation_jobs)) continue;

        $has_updates = false;

        foreach ($translation_jobs as $lang_code => $job_info) {
            
            // Skip completed/failed jobs
            if (isset($job_info['status']) && in_array($job_info['status'], ['completed', 'failed'])) {
                continue;
            }

            $job_id = $job_info['jobId'] ?? '';
            if (!$job_id) continue;

            // A. Call Node API to check status (Updated Constant)
            $api_url = EONSR_AEO_AGENT_API_URL . "/api/v1/article/job/{$job_id}";
            $response = wp_remote_get($api_url, ['timeout' => 15]);

            if (is_wp_error($response)) continue;

            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!$data || !$data['success']) continue;

            $remote_job = $data['job'];
            $status     = $remote_job['status'] ?? 'unknown';

            // Update status if changed
            if ($status !== ($job_info['status'] ?? '')) {
                $translation_jobs[$lang_code]['status'] = $status;
                $has_updates = true;
            }

            // B. Handle Completed Job
            if ($status === 'completed') {
                try {
                    $result = $remote_job['result']; // New Translated Content

                    // --- Reuse Media from Source Post ---
                    $original_thumb_id       = get_post_thumbnail_id($source_post_id);
                    // Updated Meta Key
                    $original_content_img_id = get_post_meta($source_post_id, '_eonsr_aeo_in_content_image_id', true);

                    // Prepare Post Data
                    $creation_data = [
                        'jobId'               => $job_id,
                        'content'             => $result['content'],
                        'metadata'            => $result['metadata'],
                        'imagePrompts'        => [], // No prompts needed (reusing media)
                        'summaries'           => $result['summaries'] ?? [],
                        'usage'               => $remote_job['usage'] ?? [],
                        'params'              => $remote_job['params'],
                        'scheduledTime'       => get_post_field('post_date_gmt', $source_post_id),
                        'language'            => $lang_code,
                        
                        // Translation Mode Flags
                        'isTranslation'       => true,
                        'sourcePostId'        => $source_post_id,
                        'featuredImageId'     => $original_thumb_id,       // Reuse Source Featured
                        'inContentImageId'    => $original_content_img_id, // Reuse Source Content Img
                        'skip_wp_translation' => true
                    ];

                    // Create Post (via Logic Handler - Updated Function Name)
                    $res = eonsr_aeo_agent_handle_post_creation_logic($creation_data);

                    if (!is_wp_error($res) && isset($res['postId'])) {
                        $translation_jobs[$lang_code]['status']      = 'completed';
                        $translation_jobs[$lang_code]['postId']      = $res['postId'];
                        $translation_jobs[$lang_code]['completedAt'] = current_time('mysql');
                        $has_updates = true;

                        /* 
                        error_log(sprintf(
                            '[EONSR AEO Translate] ✅ Created Post #%d (%s) using Media from Source #%d',
                            $res['postId'],
                            $lang_code,
                            $source_post_id
                        )); 
                        */
                    }

                } catch (Exception $e) {
                    $translation_jobs[$lang_code]['status'] = 'failed';
                    $has_updates = true;
                    // error_log('[EONSR AEO Translate] ❌ Creation Failed: ' . $e->getMessage());
                }

            } elseif ($status === 'failed') {
                $translation_jobs[$lang_code]['status'] = 'failed';
                $has_updates = true;
            }
        }

        // Save updates to meta
        if ($has_updates) {
            // Updated Meta Key
            update_post_meta($source_post_id, '_eonsr_aeo_translation_jobs', $translation_jobs);
        }
    }
});

/* ==========================================================================
   SECTION 3: CLEANUP WORKER
   ========================================================================== */

/**
 * Cleanup Worker: Removes completed/failed job entries older than 24 hours.
 * Runs after the main polling worker (Priority 20).
 */
add_action('eonsr_aeo_agent_poll_translation_jobs', function () {
    
    // FIX: Replaced direct $wpdb query with get_posts() to satisfy "DirectDatabaseQuery" rule
    $post_ids = get_posts([
        'post_type'      => 'any', // Check all post types
        'post_status'    => 'any', // Check all statuses (publish, draft, etc.)
        'meta_key'       => '_eonsr_aeo_translation_jobs',
        'posts_per_page' => 50,    // Limit processing to 50 items per minute for performance
        'fields'         => 'ids', // Only fetch IDs for speed
        'no_found_rows'  => true,  // Skip pagination count
        'update_post_meta_cache' => false, 
        'update_post_term_cache' => false,
    ]);

    if (empty($post_ids)) {
        return;
    }

    foreach ($post_ids as $post_id) {
        // Fetch meta using standard WP function
        $jobs = get_post_meta($post_id, '_eonsr_aeo_translation_jobs', true);
        
        if (!is_array($jobs)) continue;

        $has_changes = false;

        foreach ($jobs as $lang => $job) {
            // Only cleanup terminal states
            if (isset($job['status']) && in_array($job['status'], ['completed', 'failed'])) {
                
                $completed_at = isset($job['completedAt']) ? strtotime($job['completedAt']) : 0;

                // Keep logs for 24 hours for debugging
                if ($completed_at && (time() - $completed_at) > 86400) {
                    unset($jobs[$lang]);
                    $has_changes = true;
                }
            }
        }

        // Update DB if cleaned
        if ($has_changes) {
            if (empty($jobs)) {
                delete_post_meta($post_id, '_eonsr_aeo_translation_jobs');
            } else {
                update_post_meta($post_id, '_eonsr_aeo_translation_jobs', $jobs);
            }
        }
    }
}, 20);