<?php
if (!defined('ABSPATH'))
    exit;

class Dori_Chatbot_Diagnostic_Utils
{
    public static function check_plugin_configuration()
    {
        $checks = array();
        $issues = array();

        try {
            $sharing_id = Dori_Chatbot_Cache_Manager::get_sharing_id();
            $checks['sharing_id_exists'] = !empty($sharing_id);
            $checks['sharing_id_value'] = !empty($sharing_id) ? self::mask_sensitive_value($sharing_id) : '';

            if (empty($sharing_id)) {
                $issues[] = 'Sharing ID is missing or empty';
            }

            $credentials = Dori_Chatbot_Cache_Manager::get_api_credentials();
            $checks['client_id_exists'] = !empty($credentials['client_id']);
            $checks['client_secret_exists'] = !empty($credentials['client_secret']);

            if (empty($credentials['client_id'])) {
                $issues[] = 'Client ID is missing';
            }
            if (empty($credentials['client_secret'])) {
                $issues[] = 'Client secret is missing';
            }

            $checks['plugin_version'] = DORI_CHATBOT_VERSION;

            $status = empty($issues) ? 'pass' : 'fail';
        } catch (Exception $e) {
            $status = 'fail';
            $issues[] = 'Error checking plugin configuration: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
        );
    }

    public static function check_woocommerce_integration()
    {
        $checks = array();
        $issues = array();
        $warnings = array();

        try {
            $woocommerce_installed = class_exists('WooCommerce');
            $checks['woocommerce_installed'] = $woocommerce_installed;

            if ($woocommerce_installed) {
                $woocommerce_version = 'unknown';
                if (function_exists('WC')) {
                    $woocommerce = WC();
                    $woocommerce_version = $woocommerce ? $woocommerce->version : 'unknown';
                }
                $checks['woocommerce_version'] = $woocommerce_version;

                $consumer_key = get_option('dori-chatbot-wc-consumer-key', '');
                $consumer_secret = get_option('dori-chatbot-wc-consumer-secret', '');
                $checks['api_keys_exist'] = !empty($consumer_key) && !empty($consumer_secret);

                if (empty($consumer_key) || empty($consumer_secret)) {
                    $issues[] = 'WooCommerce API keys are missing';
                }

                try {
                    $api_keys_valid = Dori_Chatbot_WooCommerce_Integration::verify_store_connection_fresh(true);
                    $checks['api_keys_valid'] = $api_keys_valid;
                    if (!$api_keys_valid) {
                        $issues[] = 'WooCommerce API keys validation failed - please verify keys are correctly configured';
                    }
                } catch (Exception $e) {
                    $checks['api_keys_valid'] = false;
                    $issues[] = 'Error validating API keys: ' . $e->getMessage();
                }

                $session_data = Dori_Chatbot_Cache_Manager::get_woocommerce_session();
                $is_rest_request = defined('REST_REQUEST') && REST_REQUEST;
                $checks['session_available'] = $session_data !== null;
                $checks['rest_api_context'] = $is_rest_request;

                if ($session_data === null) {
                    if ($is_rest_request) {
                        $warnings[] = 'INFO: WooCommerce session not available during diagnostic check (expected during REST API requests). Session functionality works normally on frontend.';
                    } else {
                        $warnings[] = 'INFO: WooCommerce session is not available - this is expected in some contexts.';
                    }
                }
            } else {
                $checks['woocommerce_version'] = null;
                $checks['api_keys_exist'] = false;
                $checks['store_connection_valid'] = false;
                $checks['session_available'] = false;
                $checks['rest_api_context'] = false;
            }

            if (!empty($issues)) {
                $status = 'fail';
            } else {
                // Check if all warnings are just INFO messages (session context is expected)
                $has_non_info_warnings = false;
                foreach ($warnings as $warning) {
                    if (strpos($warning, 'INFO:') !== 0) {
                        $has_non_info_warnings = true;
                        break;
                    }
                }

                if (!empty($warnings) && $has_non_info_warnings) {
                    $status = 'warning';
                } else {
                    $status = !$woocommerce_installed ? 'not_applicable' : 'pass';
                }
            }
        } catch (Exception $e) {
            $status = 'fail';
            $issues[] = 'Error checking WooCommerce integration: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
            'warnings' => $warnings,
        );
    }

    public static function check_frontend_injection()
    {
        $checks = array();
        $issues = array();

        try {
            global $wp_filter;
            $wp_head_exists = isset($wp_filter['wp_head']) && !empty($wp_filter['wp_head']->callbacks);
            $checks['wp_head_hook_exists'] = $wp_head_exists;

            if (!$wp_head_exists) {
                $issues[] = 'wp_head hook is not available - theme may not call wp_head()';
            }

            $inject_script_registered = has_action('wp_head', 'dori_chatbot_inject_script');
            $checks['inject_script_registered'] = $inject_script_registered;

            if (!$inject_script_registered) {
                $issues[] = 'dori_chatbot_inject_script is not registered to wp_head hook';
            }

            $resource_hints_registered = has_action('wp_head', 'dori_chatbot_resource_hints');
            $checks['resource_hints_registered'] = $resource_hints_registered;

            if (!$resource_hints_registered) {
                $issues[] = 'dori_chatbot_resource_hints is not registered to wp_head hook';
            }

            $shortcode_registered = shortcode_exists('dori-chatbot');
            $checks['shortcode_registered'] = $shortcode_registered;

            if (!$shortcode_registered) {
                $issues[] = 'dori-chatbot shortcode is not registered';
            }

            $status = empty($issues) ? 'pass' : 'fail';
        } catch (Exception $e) {
            $status = 'fail';
            $issues[] = 'Error checking frontend injection: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
        );
    }

    public static function check_product_detection()
    {
        $checks = array();
        $issues = array();

        try {
            $current_product_id = Dori_Chatbot_Cache_Manager::get_current_product_id();
            $checks['current_product_id'] = $current_product_id ? $current_product_id : null;

            $product_count = Dori_Chatbot_Cache_Manager::get_product_count();
            $checks['product_count'] = $product_count;

            if ($product_count === 0) {
                $issues[] = 'No products found in store';
            }

            $is_product_page = function_exists('is_product') ? is_product() : false;
            $checks['is_product_page'] = $is_product_page;

            $status = empty($issues) ? 'pass' : 'warning';
        } catch (Exception $e) {
            $status = 'warning';
            $issues[] = 'Error checking product detection: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
        );
    }

    public static function check_cache_performance()
    {
        $checks = array();
        $issues = array();

        try {
            $detected_plugins = array();

            if (function_exists('rocket_clean_domain')) {
                $detected_plugins[] = 'WP Rocket';
            }
            if (function_exists('w3tc_flush_all')) {
                $detected_plugins[] = 'W3 Total Cache';
            }
            if (function_exists('litespeed_purge_all')) {
                $detected_plugins[] = 'LiteSpeed Cache';
            }
            if (class_exists('autoptimizeMain')) {
                $detected_plugins[] = 'Autoptimize';
            }
            if (class_exists('WP_Optimize')) {
                $detected_plugins[] = 'WP-Optimize';
            }

            $checks['detected_caching_plugins'] = $detected_plugins;

            $widget_exclusions_configured = true;
            if (!empty($detected_plugins)) {
                $widget_url = Dori_Chatbot_API_Constants::get_widget_url();
                $widget_host = parse_url($widget_url, PHP_URL_HOST);
                $widget_path = parse_url($widget_url, PHP_URL_PATH);
                $widget_base_path = !empty($widget_path) ? trim(dirname($widget_path), '/') : '';
                $widget_host_path = !empty($widget_host) ? $widget_host . (!empty($widget_base_path) ? '/' . $widget_base_path : '') : '';
                $widget_patterns = array(
                    $widget_url,
                    'mori-chat-widget',
                    'mori-react-widget',
                );
                if (!empty($widget_host_path)) {
                    $widget_patterns[] = $widget_host_path;
                }

                if (function_exists('rocket_clean_domain')) {
                    $exclude_js = get_option('rocket_exclude_js', array());
                    $found = false;
                    foreach ($widget_patterns as $pattern) {
                        if (in_array($pattern, $exclude_js, true)) {
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        $widget_exclusions_configured = false;
                        $issues[] = 'WP Rocket: Widget script exclusions not configured';
                    }
                }

                if (class_exists('autoptimizeMain')) {
                    $exclude_js = get_option('autoptimize_js_exclude', '');
                    $found = false;
                    foreach ($widget_patterns as $pattern) {
                        if (strpos($exclude_js, $pattern) !== false) {
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        $widget_exclusions_configured = false;
                        $issues[] = 'Autoptimize: Widget script exclusions not configured';
                    }
                }
            }

            $checks['widget_exclusions_configured'] = $widget_exclusions_configured;

            $object_cache_enabled = function_exists('wp_cache_flush');
            $checks['object_cache_enabled'] = $object_cache_enabled;

            $status = empty($issues) ? 'pass' : 'warning';
        } catch (Exception $e) {
            $status = 'warning';
            $issues[] = 'Error checking cache performance: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
        );
    }

    public static function check_cdn_network()
    {
        $checks = array();
        $issues = array();

        try {
            $cdn_url = Dori_Chatbot_API_Constants::get_widget_url();

            $response = wp_remote_head($cdn_url, array(
                'timeout' => 5,
                'sslverify' => true,
            ));

            if (is_wp_error($response)) {
                $checks['cdn_accessible'] = false;
                $checks['cdn_response_code'] = 0;
                $issues[] = 'CDN is not accessible: ' . $response->get_error_message();
            } else {
                $response_code = wp_remote_retrieve_response_code($response);
                $checks['cdn_accessible'] = $response_code === 200;
                $checks['cdn_response_code'] = $response_code;

                if ($response_code !== 200) {
                    $issues[] = 'CDN returned HTTP ' . $response_code;
                }
            }

            $dns_prefetch_configured = has_action('wp_head', 'dori_chatbot_resource_hints');
            $checks['dns_prefetch_configured'] = $dns_prefetch_configured;

            if (!$dns_prefetch_configured) {
                $issues[] = 'DNS prefetch/preconnect hints not configured';
            }

            $status = empty($issues) ? 'pass' : 'fail';
        } catch (Exception $e) {
            $status = 'fail';
            $issues[] = 'Error checking CDN network: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
        );
    }

    public static function check_endpoint_reachability()
    {
        $checks = array();
        $issues = array();
        $warnings = array();

        // Use a shorter timeout for diagnostic probes (5s instead of standard 15s)
        $probe_timeout = 5;

        $targets = array(
            'widget_cdn' => esc_url_raw(Dori_Chatbot_API_Constants::get_widget_url()),
            'standard_api' => esc_url_raw(Dori_Chatbot_API_Constants::get_server_base_url()),
            'crawler_api' => esc_url_raw(Dori_Chatbot_API_Constants::get_crawler_base_url()),
            'mori_style' => esc_url_raw(Dori_Chatbot_API_Constants::get_mori_style_base_url()),
        );

        foreach ($targets as $key => $url) {
            $result = self::probe_endpoint($url, $probe_timeout);
            $checks[$key] = $result;

            if (!$result['reachable']) {
                $issues[] = sprintf('%s is not reachable (%s)', $key, $result['error']);
                continue;
            }

            if ($result['http_code'] >= 400) {
                $warnings[] = sprintf('%s returned HTTP %d', $key, $result['http_code']);
            }
        }

        if (!empty($issues)) {
            $status = 'fail';
        } elseif (!empty($warnings)) {
            $status = 'warning';
        } else {
            $status = 'pass';
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
            'warnings' => $warnings,
        );
    }

    public static function check_javascript_environment()
    {
        $checks = array();
        $issues = array();

        try {
            $nonce = wp_create_nonce('dori_thread_session');
            $checks['nonce_generation_works'] = !empty($nonce);

            if (empty($nonce)) {
                $issues[] = 'Nonce generation failed';
            }

            $ajax_url = admin_url('admin-ajax.php');
            $checks['ajax_url_available'] = !empty($ajax_url);

            if (empty($ajax_url)) {
                $issues[] = 'AJAX URL is not available';
            }

            $is_https = is_ssl() || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on');
            $checks['site_uses_https'] = $is_https;

            if (!$is_https) {
                $issues[] = 'Site is not using HTTPS - may cause mixed content warnings';
            }

            $status = empty($issues) ? 'pass' : 'fail';
        } catch (Exception $e) {
            $status = 'fail';
            $issues[] = 'Error checking JavaScript environment: ' . $e->getMessage();
        }

        return array(
            'status' => $status,
            'checks' => $checks,
            'issues' => $issues,
        );
    }

    public static function simulate_widget_config()
    {
        $config = array();
        $issues = array();
        $would_inject = false;

        try {
            $sharing_id = Dori_Chatbot_Cache_Manager::get_sharing_id();

            if (empty($sharing_id)) {
                $issues[] = 'Sharing ID is empty - widget would not inject';
            } else {
                $product_id = Dori_Chatbot_Cache_Manager::get_current_product_id();

                $config = array(
                    'sharingID' => self::mask_sensitive_value($sharing_id),
                    'productID' => !empty($product_id) ? $product_id : null,
                    'ajaxurl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('dori_thread_session'),
                    'pluginVersion' => DORI_CHATBOT_VERSION,
                );

                $would_inject = true;
            }
        } catch (Exception $e) {
            $issues[] = 'Error simulating widget config: ' . $e->getMessage();
        }

        $status = empty($issues) ? 'pass' : 'fail';

        return array(
            'status' => $status,
            'config' => $config,
            'would_inject' => $would_inject,
            'issues' => $issues,
        );
    }

    public static function determine_overall_status($diagnostics)
    {
        $has_critical_failures = false;
        $has_warnings = false;

        foreach ($diagnostics as $category => $data) {
            if (!isset($data['status'])) {
                continue;
            }

            if ($data['status'] === 'fail') {
                if (in_array($category, array('plugin_configuration', 'frontend_injection', 'cdn_network', 'endpoint_reachability', 'javascript_environment'))) {
                    $has_critical_failures = true;
                }
            } elseif ($data['status'] === 'warning') {
                $has_warnings = true;
            }
        }

        if ($has_critical_failures) {
            return 'critical';
        } elseif ($has_warnings) {
            return 'warning';
        } else {
            return 'healthy';
        }
    }

    public static function generate_recommendations($diagnostics)
    {
        $recommendations = array();

        if (isset($diagnostics['plugin_configuration']['issues']) && !empty($diagnostics['plugin_configuration']['issues'])) {
            $recommendations[] = 'Configure plugin settings: sharing ID and API credentials are required';
        }

        if (isset($diagnostics['frontend_injection']['issues']) && !empty($diagnostics['frontend_injection']['issues'])) {
            $recommendations[] = 'Verify theme includes wp_head() hook';
        }

        if (isset($diagnostics['cache_performance']['issues']) && !empty($diagnostics['cache_performance']['issues'])) {
            $recommendations[] = 'Configure caching plugin exclusions for widget script';
        }

        if (isset($diagnostics['cdn_network']['issues']) && !empty($diagnostics['cdn_network']['issues'])) {
            $recommendations[] = 'Check network connectivity and CDN accessibility';
        }

        if (isset($diagnostics['endpoint_reachability']['issues']) && !empty($diagnostics['endpoint_reachability']['issues'])) {
            $recommendations[] = 'Check outbound network access to Mori service endpoints from this host';
        }

        if (isset($diagnostics['woocommerce_integration']['issues']) && !empty($diagnostics['woocommerce_integration']['issues'])) {
            $recommendations[] = 'Verify WooCommerce API keys are correctly generated and configured with read_write permissions';
        }

        if (isset($diagnostics['woocommerce_integration']['warnings']) && !empty($diagnostics['woocommerce_integration']['warnings'])) {
            foreach ($diagnostics['woocommerce_integration']['warnings'] as $warning) {
                if (strpos($warning, 'INFO:') === 0) {
                    continue;
                }
                $recommendations[] = 'WooCommerce: ' . $warning;
            }
        }

        if (empty($recommendations)) {
            $recommendations[] = 'All diagnostic checks passed - widget should load correctly';
        } else {
            $recommendations[] = 'Clear all caches after configuration changes';
        }

        return $recommendations;
    }

    private static function mask_sensitive_value($value)
    {
        if (empty($value) || strlen($value) <= 8) {
            return str_repeat('*', strlen($value));
        }

        $first_chars = substr($value, 0, 4);
        $last_chars = substr($value, -4);
        $middle_chars = str_repeat('*', max(4, strlen($value) - 8));

        return $first_chars . $middle_chars . $last_chars;
    }

    private static function probe_endpoint($url, $timeout)
    {
        $result = array(
            'url' => esc_url_raw($url),
            'http_code' => 0,
            'reachable' => false,
            'error' => '',
        );

        $args = array(
            'timeout' => max(1, (int) $timeout),
            'redirection' => 2,
            'sslverify' => true,
        );

        $response = wp_remote_head($url, $args);
        if (is_wp_error($response)) {
            $result['error'] = $response->get_error_message();
            return $result;
        }

        $response_code = (int) wp_remote_retrieve_response_code($response);
        if ($response_code === 405 || $response_code === 501) {
            $get_args = $args;
            $get_args['limit_response_size'] = 1024;
            $response = wp_remote_get($url, $get_args);
            if (!is_wp_error($response)) {
                $response_code = (int) wp_remote_retrieve_response_code($response);
            } else {
                $result['error'] = $response->get_error_message();
                return $result;
            }
            $result['http_code'] = $response_code;
            $result['reachable'] = $response_code > 0;
            return $result;
        }

        $result['http_code'] = $response_code;
        $result['reachable'] = $response_code > 0;
        return $result;
    }
}
