<?php

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

/**
 * This file depends on WordPress core functionality.
 * The following functions and classes are defined by WordPress and will be available at runtime:
 * - current_time: Function to get the current WordPress time
 * - wp_remote_get: Function to make HTTP GET requests
 * - is_wp_error: Function to check if a value is a WP_Error
 * - wp_remote_retrieve_body: Function to get body content from an HTTP response
 * - get_edit_post_link: Function to get the edit link for a post
 * - ContentCraftAI_PostCreationManager: Class for creating posts from API responses
 */

// Require the base controller
require_once dirname(__FILE__) . '/BaseController.php';

// Require the PostCreationManager
if (!class_exists('ContentCraftAI_PostCreationManager')) {
    require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/PostCreationManager.php';
}

/**
 * Class ContentCraftAI_StatusCheckController
 * 
 * Handles checking the status of generated articles for the Content Craft AI plugin.
 */
class ContentCraftAI_StatusCheckController extends ContentCraftAI_BaseController
{
    /**
     * Instance of this class.
     *
     * @var ContentCraftAI_StatusCheckController
     */
    private static $instance = null;

    /**
     * Get an instance of this class.
     *
     * @return ContentCraftAI_StatusCheckController
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        // Private constructor to prevent direct instantiation
    }

    /**
     * Check the status of a single article generation
     * 
     * @param string $queue_id The queue ID of the article to check
     * @return array The result of the status check
     */
    public function check_article_status($queue_id)
    {
        // Get article manager
        $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();

        // Get generation from database
        $generation = $article_manager->get_generation_by_queue_id($queue_id);

        try {
            if (empty($queue_id)) {
                return [
                    'success' => false,
                    'message' => 'Queue ID is required',
                    'code' => 400
                ];
            }

            if (!$generation) {
                return [
                    'success' => false,
                    'message' => 'Article generation not found',
                    'code' => 404
                ];
            }

            // Get parameters to check for API queue ID
            $parameters = json_decode($generation->parameters, true) ?: [];
            $api_queue_id = $parameters['apiQueueId'] ?? null;

            // If article is already completed or failed, return database status
            if (in_array($generation->status, ['completed', 'failed', 'cancelled'])) {
                return [
                    'success' => true,
                    'message' => 'Article status retrieved',
                    'data' => [
                        'queueId' => $queue_id,
                        'status' => $generation->status,
                        'title' => $generation->title,
                        'errorMessage' => $parameters['error_message'] ?? null,
                        'postId' => $generation->post_id,
                        'editUrl' => $generation->post_id ? get_edit_post_link($generation->post_id, '') : null
                    ]
                ];
            }

            // If the article is scheduled and not yet due
            if ($generation->status === 'scheduled' && !empty($generation->scheduled_time)) {
                $now = current_time('mysql');
                $scheduled_time = $generation->scheduled_time;

                if ($scheduled_time > $now) {
                    return [
                        'success' => true,
                        'message' => 'Article scheduled for future generation',
                        'data' => [
                            'queueId' => $queue_id,
                            'status' => 'scheduled',
                            'title' => $generation->title,
                            'scheduledTime' => $scheduled_time
                        ]
                    ];
                }
            }

            // For pending or processing articles, check with the API if we have an API queue ID
            if ($api_queue_id) {
                // Call the API to check the article generation status
                $api_response = content_craft_ai_api_check_status($api_queue_id);

                if ($api_response && isset($api_response['success']) && $api_response['success']) {
                    $api_status = $api_response['data']['status'] ?? 'unknown';
                    $api_error = $api_response['data']['error'] ?? null;
                    $api_result_data = $api_response['data']['result'] ?? null;

                    // Handle different API statuses
                    if ($api_status === 'completed') {
                        if ($api_result_data && isset($api_result_data['content']['fullContent'])) {

                            // error_log('Content Craft AI: Article is complete and content is present - creating WordPress post');
                            // error_log('Content Craft AI: API result data (for post creation): ' . print_r($api_result_data, true));
                            // Article is complete and content is present - create WordPress post
                            $post_manager = ContentCraftAI_PostCreationManager::get_instance();
                            $post_id = $post_manager->create_post_from_content($queue_id, $api_result_data);

                            if ($post_id) {
                                // Update status to completed
                                $article_manager->update_generation_status($queue_id, 'completed', $post_id);

                                // Note: PostCreationManager already sends the notification
                                // No need to send notification here to avoid duplicates

                                return [
                                    'success' => true,
                                    'message' => 'Article generation completed and post created',
                                    'data' => [
                                        'queueId' => $queue_id,
                                        'status' => 'completed',
                                        'title' => $generation->title,
                                        'postId' => $post_id,
                                        'editUrl' => get_edit_post_link($post_id, '')
                                    ]
                                ];
                            } else {
                                // Handle post creation failure
                                $article_manager->update_generation_status($queue_id, 'failed');
                                // error_log('Content Craft AI: Failed to create post from article content for queue ID: ' . $queue_id);

                                // Note: PostCreationManager already sends failure notification
                                // No need to send notification here to avoid duplicates

                                return [
                                    'success' => false,
                                    'message' => 'Failed to create WordPress post',
                                    'data' => [
                                        'queueId' => $queue_id,
                                        'status' => 'failed',
                                        'errorMessage' => 'Failed to create WordPress post'
                                    ]
                                ];
                            }
                        } else {
                            // Article is marked 'completed' by API, but no content provided
                            $error_message_no_content = 'API reported completion but content was missing.';
                            $article_manager->update_generation_status($queue_id, 'failed');
                            // Potentially log $error_message_no_content or add to parameters

                            return [
                                'success' => false,
                                'message' => $error_message_no_content,
                                'data' => [
                                    'queueId' => $queue_id,
                                    'status' => 'failed',
                                    'errorMessage' => $error_message_no_content
                                ]
                            ];
                        }
                    } elseif ($api_status === 'failed' || $api_status === 'error') {
                        // Update status to failed in our database
                        $article_manager->update_generation_status($queue_id, 'failed');
                        // error_log('Content Craft AI: Article generation failed with status: ' . $api_status . ', error: ' . ($api_error ?? 'Unknown error'));

                        // Send failure notification - this is the only place we send notification for API errors
                        if (function_exists('content_craft_ai_notify_article_failed')) {
                            content_craft_ai_notify_article_failed($queue_id, $api_error ?? 'API returned error status');
                        }

                        return [
                            'success' => false,
                            'message' => 'Article generation failed',
                            'data' => [
                                'queueId' => $queue_id,
                                'status' => 'failed',
                                'errorMessage' => $api_error ?? 'API returned error status'
                            ]
                        ];
                    } else {
                        // Article is still genuinely pending or processing, or an unknown status from API
                        return [
                            'success' => true,
                            'message' => 'Article generation is in progress or status is ' . ($generation->status ?? 'processing'),
                            'data' => [
                                'queueId' => $queue_id,
                                'status' => $generation->status, // Use the stored status from the database
                                'title' => $generation->title
                            ]
                        ];
                    }
                } else {
                    // API call failed or returned an error
                    // error_log('Content Craft AI: Failed to check article status for queue ID: ' . $queue_id);

                    // Mark the article as failed
                    $article_manager->update_generation_status($queue_id, 'failed');

                    // Send failure notification - only here, not in PostCreationManager
                    if (function_exists('content_craft_ai_notify_article_failed')) {
                        $error_message = isset($api_response['message']) ?
                            'API Error: ' . $api_response['message'] :
                            'Status check failed: API error or no response';

                        content_craft_ai_notify_article_failed($queue_id, $error_message);
                    }

                    // Return failure
                    return [
                        'success' => false,
                        'message' => 'API error during status check',
                        'data' => [
                            'queueId' => $queue_id,
                            'status' => 'failed',
                            'errorMessage' => isset($api_response['message']) ? $api_response['message'] : 'API error'
                        ]
                    ];
                }
            } else {
                // No API queue ID available, return database status
                return [
                    'success' => true,
                    'message' => 'Article status retrieved from local database',
                    'data' => [
                        'queueId' => $queue_id,
                        'status' => $generation->status,
                        'title' => $generation->title
                    ]
                ];
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage(),
                'code' => 500
            ];
        }
    }

    /**
     * Check the status of pending article generations in the database
     * and update their status by checking with the API
     * 
     * @return array Statistics about the status check operations
     */
    public function check_pending_statuses()
    {
        try {
            // Get pending generations from the database
            $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
            $pending_generations = $article_manager->get_pending_generations(10);

            $stats = [
                'total' => count($pending_generations),
                'checked' => 0,
                'completed' => 0,
                'failed' => 0,
                'still_pending' => 0
            ];

            if (empty($pending_generations)) {
                return $stats;
            }

            // Check status of each pending generation
            foreach ($pending_generations as $generation) {
                $parameters = json_decode($generation->parameters, true) ?: [];
                $api_queue_id = $parameters['apiQueueId'] ?? null;

                if (!$api_queue_id) {
                    // No API queue ID, cant check status
                    $stats['still_pending']++;
                    continue;
                }

                $result = $this->check_article_status($generation->queue_id);
                $stats['checked']++;

                if ($result['success'] && isset($result['data']['status'])) {
                    $status = $result['data']['status'];

                    if ($status === 'completed') {
                        $stats['completed']++;
                    } elseif ($status === 'failed') {
                        $stats['failed']++;
                    } else {
                        $stats['still_pending']++;
                    }
                } else {
                    $stats['still_pending']++;
                }
            }

            return $stats;
        } catch (Exception $e) {
            // error_log('Content Craft AI: Error checking pending statuses - ' . $e->getMessage());

            return [
                'total' => 0,
                'checked' => 0,
                'completed' => 0,
                'failed' => 0,
                'still_pending' => 0,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Get article generation history with pagination and filtering
     * 
     * @param int $page Page number
     * @param int $per_page Items per page
     * @param array $filters Filter criteria
     * @return array Article generation history data
     */
    public function get_generation_history($page = 1, $per_page = 10, $filters = [])
    {
        // Get the article manager instance
        $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();

        // Call the manager's method to get paginated generations with filters
        $history = $article_manager->get_paginated_generations($page, $per_page, $filters);

        return $history;
    }
}
