<?php
/**
 * System Diagnostics
 *
 * Provides system health checks and intelligent suggestions for users
 *
 * @package AIContentGenerator
 */

namespace AICG;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handles system diagnostics and suggestions
 */
class System_Diagnostics
{
    /**
     * Diagnostic status constants
     */
    const STATUS_OK = 'ok';
    const STATUS_WARNING = 'warning';
    const STATUS_ERROR = 'error';
    const STATUS_INFO = 'info';

    /**
     * Check WP-Cron status
     */
    public static function check_cron_status()
    {
        $result = array(
            'name' => 'WP-Cron Status',
            'status' => self::STATUS_OK,
            'message' => 'WP-Cron is working properly.',
            'details' => array(),
        );

        // Check if DISABLE_WP_CRON is set
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            $result['status'] = self::STATUS_WARNING;
            $result['message'] = 'WP-Cron is disabled. Make sure you have an external cron job configured.';
            $result['details'][] = 'DISABLE_WP_CRON is set to true in wp-config.php';
        }

        // Check last cron run
        $last_cron_check = get_option('roidaico_last_cron_check', 0);
        if ($last_cron_check) {
            $time_diff = time() - $last_cron_check;
            $result['details'][] = sprintf('Last cron check: %s ago', human_time_diff($last_cron_check));
            
            if ($time_diff > 3600) { // More than 1 hour
                $result['status'] = self::STATUS_WARNING;
                $result['message'] = 'Cron has not run in over an hour.';
            }
        } else {
            $result['details'][] = 'Cron has not run yet.';
        }

        // Check for pending cron events
        $crons = _get_cron_array();
        $roidaico_events = 0;
        $overdue_events = 0;
        $now = time();

        if (!empty($crons)) {
            foreach ($crons as $timestamp => $hooks) {
                foreach ($hooks as $hook => $args) {
                    if (strpos($hook, 'roidaico_') === 0) {
                        $roidaico_events++;
                        if ($timestamp < $now) {
                            $overdue_events++;
                        }
                    }
                }
            }
        }

        $result['details'][] = sprintf('Scheduled AICG events: %d', $roidaico_events);
        
        if ($overdue_events > 0) {
            $result['details'][] = sprintf('Overdue events: %d', $overdue_events);
            if ($overdue_events > 5) {
                $result['status'] = self::STATUS_ERROR;
                $result['message'] = 'Multiple cron events are overdue. WP-Cron may not be triggering properly.';
            }
        }

        return $result;
    }

    /**
     * Check API keys status
     */
    public static function check_api_keys()
    {
        $result = array(
            'name' => 'API Configuration',
            'status' => self::STATUS_OK,
            'message' => 'All required API configurations are correct.',
            'details' => array(),
        );

        $provider = get_option('roidaico_ai_provider', 'openrouter');
        $pexels_key = get_option('roidaico_pexels_api_key', '');

        if ($provider === 'wp_ai_client') {
            if (!function_exists('wp_ai_client_prompt')) {
                $result['status'] = self::STATUS_ERROR;
                $result['message'] = 'WordPress AI Client is selected but not supported on this version of WordPress.';
                $result['details'][] = 'AI Client: Unsupported (Requires WP 7.0+)';
            } else {
                $ai_client = new Ai_Client();
                $test = $ai_client->test_connection();
                if (is_wp_error($test)) {
                    $result['status'] = self::STATUS_ERROR;
                    $result['message'] = 'WordPress AI Client integration failed: ' . $test->get_error_message();
                    $result['details'][] = 'AI Client: Configuration failed';
                } else {
                    $result['details'][] = 'AI Client: Connected successfully (WordPress Native)';
                }
            }
        } else {
            $openrouter_key = get_option('roidaico_openrouter_api_key', '');
            if (empty($openrouter_key)) {
                $result['status'] = self::STATUS_ERROR;
                $result['message'] = 'OpenRouter API key is not configured.';
                $result['details'][] = 'OpenRouter API: Not configured';
            } else {
                $openrouter = new Openrouter_Api();
                $test = $openrouter->test_connection();
                if (is_wp_error($test)) {
                    $result['status'] = self::STATUS_ERROR;
                    $result['message'] = 'OpenRouter API connection failed: ' . $test->get_error_message();
                    $result['details'][] = 'OpenRouter API: Connection failed';
                } else {
                    $result['details'][] = 'OpenRouter API: Connected successfully';
                }
            }
        }

        if (empty($pexels_key)) {
            if ($result['status'] !== self::STATUS_ERROR) {
                $result['status'] = self::STATUS_WARNING;
                $result['message'] = 'Pexels API key is not configured. Images will not be added to articles.';
            }
            $result['details'][] = 'Pexels API: Not configured (optional)';
        } else {
            $pexels = new Pexels_Api();
            $test = $pexels->test_connection();
            if (is_wp_error($test)) {
                if ($result['status'] !== self::STATUS_ERROR) {
                    $result['status'] = self::STATUS_WARNING;
                }
                $result['message'] = 'Pexels API connection failed: ' . $test->get_error_message();
                $result['details'][] = 'Pexels API: Connection failed';
            } else {
                $result['details'][] = 'Pexels API: Connected successfully';
            }
        }

        if ($provider === 'wp_ai_client') {
            $result['details'][] = 'Selected Model: Managed by WordPress';
        } else {
            $model = get_option('roidaico_openrouter_model', 'openai/gpt-4o-mini');
            $result['details'][] = sprintf('Selected Model: %s', $model);
        }

        return $result;
    }

    /**
     * Check pending keywords status
     */
    public static function check_pending_keywords()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'roidaico_keywords';

        $result = array(
            'name' => 'Keywords Queue',
            'status' => self::STATUS_OK,
            'message' => 'Keywords queue is healthy.',
            'details' => array(),
        );

        // Count keywords by status
        $stats = $wpdb->get_results(
            "SELECT status, COUNT(*) as count FROM $table GROUP BY status"
        );

        $counts = array();
        foreach ($stats as $stat) {
            $counts[$stat->status] = (int) $stat->count;
        }

        $pending = $counts['pending'] ?? 0;
        $processing = $counts['processing'] ?? 0;
        $completed = $counts['completed'] ?? 0;
        $failed = $counts['failed'] ?? 0;

        $result['details'][] = sprintf('Pending: %d', $pending);
        $result['details'][] = sprintf('Processing: %d', $processing);
        $result['details'][] = sprintf('Completed: %d', $completed);
        $result['details'][] = sprintf('Failed: %d', $failed);

        // Check for stuck processing keywords (older than 30 minutes)
        $stuck = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE status = 'processing' AND processed_at < %s",
            gmdate('Y-m-d H:i:s', strtotime('-30 minutes'))
        ));

        if ($stuck > 0) {
            $result['status'] = self::STATUS_WARNING;
            $result['message'] = sprintf('%d keywords appear to be stuck in processing.', $stuck);
            $result['details'][] = sprintf('Stuck in processing: %d', $stuck);
        }

        if ($failed > 0) {
            $result['status'] = self::STATUS_WARNING;
            $result['message'] = sprintf('%d keywords have failed. Check the logs for details.', $failed);
        }

        if ($pending === 0 && $completed === 0 && $processing === 0) {
            $result['status'] = self::STATUS_INFO;
            $result['message'] = 'No keywords in queue. Add keywords to start generating content.';
        }

        return $result;
    }

    /**
     * Check ready articles (drafts) status
     */
    public static function check_ready_articles()
    {
        $result = array(
            'name' => 'Ready Articles Buffer',
            'status' => self::STATUS_OK,
            'message' => 'Article buffer is healthy.',
            'details' => array(),
        );

        $max_ready = (int) get_option('roidaico_max_ready_articles', 5);
        
        // Count drafts with roidaico_generated meta
        $drafts = get_posts(array(
            'post_type' => 'post',
            'post_status' => 'draft',
            'meta_key' => '_roidaico_generated',
            'meta_value' => '1',
            'numberposts' => -1,
            'fields' => 'ids',
        ));

        $draft_count = count($drafts);
        $result['details'][] = sprintf('Ready drafts: %d', $draft_count);
        $result['details'][] = sprintf('Maximum allowed: %d', $max_ready);

        if ($draft_count >= $max_ready) {
            $result['status'] = self::STATUS_INFO;
            $result['message'] = 'Buffer is full. New articles will be generated after publishing.';
        } elseif ($draft_count === 0) {
            $result['status'] = self::STATUS_INFO;
            $result['message'] = 'No ready articles. Generation will start when keywords are added.';
        } else {
            $result['details'][] = sprintf('Available slots: %d', $max_ready - $draft_count);
        }

        return $result;
    }

    /**
     * Check schedules status
     */
    public static function check_schedules()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'roidaico_schedules';

        $result = array(
            'name' => 'Publishing Schedules',
            'status' => self::STATUS_OK,
            'message' => 'Schedules are configured properly.',
            'details' => array(),
        );

        $total = $wpdb->get_var("SELECT COUNT(*) FROM $table");
        $enabled = $wpdb->get_var("SELECT COUNT(*) FROM $table WHERE enabled = 1");

        $result['details'][] = sprintf('Total schedules: %d', $total);
        $result['details'][] = sprintf('Enabled: %d', $enabled);

        if ($total == 0) {
            $result['status'] = self::STATUS_WARNING;
            $result['message'] = 'No publishing schedules configured. Create a schedule to start auto-publishing.';
        } elseif ($enabled == 0) {
            $result['status'] = self::STATUS_WARNING;
            $result['message'] = 'All schedules are disabled. Enable a schedule to start publishing.';
        }

        return $result;
    }

    /**
     * Check database tables
     */
    public static function check_database()
    {
        global $wpdb;

        $result = array(
            'name' => 'Database Tables',
            'status' => self::STATUS_OK,
            'message' => 'All database tables exist.',
            'details' => array(),
        );

        $tables = array(
            'roidaico_keywords',
            'roidaico_schedules',
            'roidaico_used_images',
            'roidaico_posts_log',
            'roidaico_logs',
        );

        $missing = array();
        foreach ($tables as $table) {
            $full_name = $wpdb->prefix . $table;
            $exists = $wpdb->get_var($wpdb->prepare(
                "SHOW TABLES LIKE %s",
                $full_name
            ));
            
            if ($exists) {
                $result['details'][] = sprintf('%s: OK', $table);
            } else {
                $missing[] = $table;
                $result['details'][] = sprintf('%s: MISSING', $table);
            }
        }

        if (!empty($missing)) {
            $result['status'] = self::STATUS_ERROR;
            $result['message'] = 'Some database tables are missing. Try deactivating and reactivating the plugin.';
        }

        return $result;
    }

    /**
     * Check image downloading capability
     */
    public static function check_image_capability()
    {
        $result = array(
            'name' => 'Image Download Capability',
            'status' => self::STATUS_OK,
            'message' => 'Server is capable of downloading images.',
            'details' => array(),
        );

        if (!function_exists('curl_init')) {
            $result['status'] = self::STATUS_ERROR;
            $result['message'] = 'PHP CURL is not installed. Image downloading will fail.';
            $result['details'][] = 'PHP extension: curl is MISSING';
        } else {
            $result['details'][] = 'PHP extension: curl is OK';
        }

        if (!ini_get('allow_url_fopen')) {
            $result['details'][] = 'allow_url_fopen: Disabled (Recommended to enable, but curl might work)';
        } else {
            $result['details'][] = 'allow_url_fopen: Enabled';
        }

        // Check if uploads directory is writable
        $upload_dir = wp_upload_dir();
        if ($upload_dir['error']) {
            $result['status'] = self::STATUS_ERROR;
            $result['message'] = 'Uploads directory is not writable.';
            $result['details'][] = 'Error: ' . $upload_dir['error'];
        } else {
            if (!is_writable($upload_dir['path'])) {
                $result['status'] = self::STATUS_ERROR;
                $result['message'] = 'Uploads directory is not writable.';
                $result['details'][] = 'Path: ' . $upload_dir['path'] . ' is NOT writable';
            } else {
                $result['details'][] = 'Uploads directory: OK';
            }
        }

        return $result;
    }

    /**
     * Get all diagnostics
     */
    public static function get_all_diagnostics()
    {
        return array(
            self::check_cron_status(),
            self::check_api_keys(),
            self::check_image_capability(),
            self::check_pending_keywords(),
            self::check_ready_articles(),
            self::check_schedules(),
            self::check_database(),
        );
    }

    /**
     * Get suggestions based on diagnostics
     */
    public static function get_suggestions()
    {
        $suggestions = array();
        $diagnostics = self::get_all_diagnostics();

        // Check for cron issues
        $cron = $diagnostics[0];
        if ($cron['status'] !== self::STATUS_OK) {
            $suggestions[] = array(
                'type' => 'warning',
                'icon' => 'clock',
                'title' => 'Improve Cron Reliability',
                'description' => 'For more reliable scheduled publishing, consider setting up an external cron job.',
                'action' => array(
                    'text' => 'Learn how to set up external cron',
                    'url' => 'https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/',
                ),
                'code' => "Add this to your crontab:\n*/5 * * * * wget -q -O - " . site_url('wp-cron.php?doing_wp_cron') . " >/dev/null 2>&1",
            );
        }

        // Check for API key issues
        $api = $diagnostics[1];
        if ($api['status'] === self::STATUS_ERROR) {
            $suggestions[] = array(
                'type' => 'error',
                'icon' => 'admin-network',
                'title' => 'Configure OpenRouter API',
                'description' => 'The OpenRouter API key is required to generate content. Get your free API key from OpenRouter.',
                'action' => array(
                    'text' => 'Go to Settings',
                    'url' => admin_url('admin.php?page=roidaico-settings'),
                ),
            );
        } elseif ($api['status'] === self::STATUS_WARNING) {
            $suggestions[] = array(
                'type' => 'info',
                'icon' => 'format-image',
                'title' => 'Add Pexels API (Optional)',
                'description' => 'Configure a Pexels API key to automatically add relevant images to your articles.',
                'action' => array(
                    'text' => 'Go to Settings',
                    'url' => admin_url('admin.php?page=roidaico-settings'),
                ),
            );
        }

        // Check for schedule issues
        $schedules = $diagnostics[5];
        if ($schedules['status'] === self::STATUS_WARNING) {
            $suggestions[] = array(
                'type' => 'warning',
                'icon' => 'calendar-alt',
                'title' => 'Set Up Publishing Schedule',
                'description' => 'Create a publishing schedule to automatically publish generated articles.',
                'action' => array(
                    'text' => 'Create Schedule',
                    'url' => admin_url('admin.php?page=roidaico-schedules'),
                ),
            );
        }

        // Check for keywords
        $keywords = $diagnostics[3];
        if ($keywords['status'] === self::STATUS_INFO && strpos($keywords['message'], 'No keywords') !== false) {
            $suggestions[] = array(
                'type' => 'info',
                'icon' => 'tag',
                'title' => 'Add Keywords to Start',
                'description' => 'Add keywords to the queue to start generating content automatically.',
                'action' => array(
                    'text' => 'Add Keywords',
                    'url' => admin_url('admin.php?page=roidaico-keywords'),
                ),
            );
        }

        // Check for database issues
        $database = $diagnostics[6];
        if ($database['status'] === self::STATUS_ERROR) {
            $suggestions[] = array(
                'type' => 'error',
                'icon' => 'database',
                'title' => 'Database Tables Missing',
                'description' => 'Some required database tables are missing. Try deactivating and reactivating the plugin.',
                'action' => array(
                    'text' => 'Go to Plugins',
                    'url' => admin_url('plugins.php'),
                ),
            );
        }

        // Check for image issues
        $image = $diagnostics[2];
        if ($image['status'] === self::STATUS_ERROR) {
            $suggestions[] = array(
                'type' => 'error',
                'icon' => 'warning',
                'title' => 'Fix Image Downloading',
                'description' => 'Your server is unable to download images. Please check if PHP CURL is installed and the uploads directory is writable.',
                'action' => array(
                    'text' => 'Check Server Health',
                    'url' => admin_url('site-health.php'),
                ),
            );
        }

        return $suggestions;
    }

    /**
     * Get system health score (0-100)
     */
    public static function get_health_score()
    {
        $diagnostics = self::get_all_diagnostics();
        $total = count($diagnostics);
        $score = 0;

        foreach ($diagnostics as $diagnostic) {
            switch ($diagnostic['status']) {
                case self::STATUS_OK:
                    $score += 100;
                    break;
                case self::STATUS_INFO:
                    $score += 75;
                    break;
                case self::STATUS_WARNING:
                    $score += 50;
                    break;
                case self::STATUS_ERROR:
                    $score += 0;
                    break;
            }
        }

        return round($score / $total);
    }
}
