<?php

namespace XZD\AI\V5\REST\Controllers;

use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\REST\Middleware\AuthMiddleware;

/**
 * 健康检查与系统信息端点
 */
class HealthController extends BaseController
{
    public function registerRoutes(): void
    {
        // GET /health — 公开
        register_rest_route($this->namespace, '/health', [
            'methods'             => 'GET',
            'callback'            => [$this, 'health'],
            'permission_callback' => '__return_true',
        ]);

        // GET /info — 管理员
        $this->registerGet('/info', [$this, 'info'], 'manage_options');

        // GET /stats/dashboard — 仪表盘统计数据
        $this->registerGet('/stats/dashboard', [$this, 'dashboardStats'], 'manage_options');

        // V3.2: 系统健康检查 + 一键清理
        $this->registerGet('/health/system-status', [$this, 'systemStatus'], 'manage_options');
        $this->registerPost('/health/cleanup', [$this, 'cleanup'], 'manage_options');
    }

    public function health(): \WP_REST_Response
    {
        return $this->success([
            'status'    => 'healthy',
            'version'   => XZD_AI_VERSION,
            'php'       => PHP_VERSION,
            'wp'        => get_bloginfo('version'),
            'time'      => current_time('mysql'),
        ]);
    }

    public function info(): \WP_REST_Response
    {
        global $wpdb;

        return $this->success([
            'version'   => XZD_AI_VERSION,
            'php'       => [
                'version' => PHP_VERSION,
                'memory_limit' => ini_get('memory_limit'),
                'max_execution_time' => ini_get('max_execution_time'),
            ],
            'wordpress' => [
                'version'    => get_bloginfo('version'),
                'site_url'   => site_url(),
                'post_count' => wp_count_posts()->publish ?? 0,
                'user_count' => count_users()['total_users'] ?? 0,
                'categories' => array_values(array_map(fn($cat) => [
                    'term_id' => $cat->term_id,
                    'name'    => $cat->name,
                    'slug'    => $cat->slug,
                    'count'   => $cat->count,
                ], get_categories(['orderby' => 'name', 'hide_empty' => false]))),
            ],
            'theme'     => [
                'name'    => wp_get_theme()->get('Name'),
                'version' => wp_get_theme()->get('Version'),
                'has_deep_adapter' => \XZD\AI\V5\Theme\AdapterRegistry::isZibll(),
            ],
            'database'  => [
                'version' => $wpdb->db_version(),
                'prefix'  => $wpdb->prefix,
                'tables'  => $this->getPluginTables(),
            ],
            'plugins'   => [
                'active' => get_option('active_plugins', []),
            ],
            'config'    => [
                'has_ai_connection' => !empty(\XZD\AI\V5\Core\Config::instance()->get('connections.text.0')),
                'tool_count'        => count(\XZD\AI\V5\Tools\ToolRegistry::instance()->getAll()),
                'provider_count'    => count(array_filter(
                    \XZD\AI\V5\Core\Config::instance()->get('connections.text', []),
                    fn($c) => !empty($c['api_key'])
                )),
            ],
            'stats'     => [
                'total_operations' => (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}xzd_ai_operation_log"),
                'total_errors_24h' => (int) $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}xzd_ai_operation_log WHERE status != 'success' AND created_at > %s",
                    date('Y-m-d H:i:s', strtotime('-24 hours'))
                )),
                'total_chat_sessions' => (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}xzd_ai_chat_sessions WHERE status = 'active'"),
                'total_chat_messages' => (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}xzd_ai_chat_messages"),
            ],
        ]);
    }

    /**
     * 仪表盘图表数据（7天趋势、分类统计、本月处理数）
     */
    public function dashboardStats(): \WP_REST_Response
    {
        global $wpdb;
        $logTable = $wpdb->prefix . 'xzd_ai_operation_log';

        // 7天趋势数据
        $trend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $count = (int) $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$logTable} WHERE DATE(created_at) = %s",
                $date
            ));
            $trend[] = ['date' => $date, 'count' => $count];
        }

        // 按分类统计（从工具注册表获取）
        $registry = \XZD\AI\V5\Tools\ToolRegistry::instance();
        $byCategory = $registry->getStats()['by_category'] ?? [];
        $catLabels = ['content' => '内容工具', 'wp' => 'WP工具', 'seo' => 'SEO工具', 'media' => '媒体工具', 'knowledge' => '知识库', 'automation' => '自动化'];
        $categories = [];
        foreach ($byCategory as $cat => $count) {
            $categories[] = ['name' => $catLabels[$cat] ?? $cat, 'count' => $count];
        }

        // AI处理总次数（本月）
        $monthStart = date('Y-m-01');
        $monthCount = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$logTable} WHERE created_at >= %s",
            $monthStart
        ));

        return $this->success([
            'trend_7d'     => $trend,
            'categories'   => $categories,
            'month_count'  => $monthCount,
        ]);
    }

    /**
     * V3.2: 系统健康状态 — 队列/AS Runner/失败任务
     */
    public function systemStatus(): \WP_REST_Response
    {
        global $wpdb;

        // 1. 队列积压
        $pendingQueue = \XZD\AI\V5\Core\Config::getArrayOption('xzd_pending_queue', []);
        $workerQueue  = \XZD\AI\V5\Core\Config::getArrayOption('xzd_worker_queue', []);
        $pendingCount = count($pendingQueue);
        $workerCount  = count($workerQueue);
        $asPending    = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='xzd_worker_process' AND status='pending'"
        );
        $totalBacklog = $pendingCount + $workerCount + $asPending;

        $queueStatus = $totalBacklog >= 50 ? 'critical' : ($totalBacklog >= 20 ? 'warning' : 'healthy');

        // 2. AS Runner 状态
        $lastRunner = $wpdb->get_row(
            "SELECT action_id, status, last_attempt_gmt FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='action_scheduler_run_queue' ORDER BY action_id DESC LIMIT 1"
        );
        $zombieRunners = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='action_scheduler_run_queue' AND status='pending' AND claim_id=0"
        );
        $runnerHealthy = $lastRunner && $lastRunner->status === 'complete';
        $lastRunTime = $lastRunner ? ($lastRunner->last_attempt_gmt !== '0000-00-00 00:00:00' ? $lastRunner->last_attempt_gmt : null) : null;

        // 3. 失败任务
        $failedCount = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='xzd_worker_process' AND status='failed'"
        );
        $permanentFailCount = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key='_xzd_ai_permanent_fail'"
        );

        // 4. 今日处理统计
        $todaySuccess = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}xzd_ai_operation_log WHERE category='pipeline' AND status='success' AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)"
        );
        $todayCost = (float) $wpdb->get_var(
            "SELECT COALESCE(SUM(cost_rmb), 0) FROM {$wpdb->prefix}xzd_ai_cost_log WHERE DATE(created_at) = CURDATE()"
        );

        // 5. 综合判断
        $suggestions = [];
        $overall = 'healthy';

        if ($failedCount > 0) {
            $overall = 'warning';
            $suggestions[] = "检测到 {$failedCount} 条失败任务，建议清理";
        }
        if ($zombieRunners > 0) {
            $overall = 'warning';
            $suggestions[] = "检测到 {$zombieRunners} 个僵尸Runner，建议清理";
        }
        if (!$runnerHealthy) {
            $overall = 'warning';
            $suggestions[] = 'AS Runner 状态异常，系统将自动尝试恢复';
        }
        if ($totalBacklog >= 50) {
            $overall = 'critical';
            $suggestions[] = "队列积压 {$totalBacklog} 条（≥50），已暂停旧文章入队";
        }
        if (empty($suggestions)) {
            $suggestions[] = '系统运行正常，无需处理';
        }

        return $this->success([
            'queue' => [
                'pending_count'  => $pendingCount,
                'worker_count'   => $workerCount,
                'as_pending'     => $asPending,
                'total_backlog'  => $totalBacklog,
                'status'         => $queueStatus,
            ],
            'runner' => [
                'healthy'       => $runnerHealthy,
                'last_run_time' => $lastRunTime,
                'zombie_count'  => $zombieRunners,
            ],
            'failed' => [
                'count'          => $failedCount,
                'permanent_fail' => $permanentFailCount,
            ],
            'today' => [
                'success_count' => $todaySuccess,
                'cost_rmb'      => round($todayCost, 4),
            ],
            'overall'     => $overall,
            'suggestions' => $suggestions,
        ]);
    }

    /**
     * V3.2: 一键清理 — 清理失败任务 + 僵尸Runner
     */
    public function cleanup(\WP_REST_Request $request): \WP_REST_Response
    {
        global $wpdb;

        $cleanFailed  = $this->getParam($request, 'clean_failed', '1') !== '0';
        $cleanZombies = $this->getParam($request, 'clean_zombies', '1') !== '0';
        $cleanStale   = $this->getParam($request, 'clean_stale', '1') !== '0';

        $results = [];

        // 1. 清理失败任务
        if ($cleanFailed) {
            $failedBefore = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='xzd_worker_process' AND status='failed'"
            );
            // 标记失败任务为 complete（不再重试）
            $wpdb->query(
                "UPDATE {$wpdb->prefix}actionscheduler_actions SET status='complete' WHERE hook='xzd_worker_process' AND status='failed'"
            );
            $failedAfter = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='xzd_worker_process' AND status='failed'"
            );
            $results['failed_cleaned'] = $failedBefore - $failedAfter;
        }

        // 2. 清理僵尸 Runner（pending 但未被 claim）
        if ($cleanZombies) {
            $zombiesBefore = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='action_scheduler_run_queue' AND status='pending' AND claim_id=0"
            );
            // 将僵尸标记为 complete，让心跳自动补调新的
            $wpdb->query(
                "UPDATE {$wpdb->prefix}actionscheduler_actions SET status='complete' WHERE hook='action_scheduler_run_queue' AND status='pending' AND claim_id=0"
            );
            $zombiesAfter = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='action_scheduler_run_queue' AND status='pending' AND claim_id=0"
            );
            $results['zombies_cleaned'] = $zombiesBefore - $zombiesAfter;
        }

        // 3. 清理过期 claim（超过10分钟未释放的孤儿 claim）
        if ($cleanStale) {
            $staleBefore = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_claims WHERE date_created_gmt < DATE_SUB(NOW(), INTERVAL 10 MINUTE)"
            );
            $wpdb->query(
                "DELETE FROM {$wpdb->prefix}actionscheduler_claims WHERE date_created_gmt < DATE_SUB(NOW(), INTERVAL 10 MINUTE)"
            );
            $staleAfter = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_claims WHERE date_created_gmt < DATE_SUB(NOW(), INTERVAL 10 MINUTE)"
            );
            $results['stale_claims_cleaned'] = $staleBefore - $staleAfter;
        }

        // 4. 清理永久失败标记（保留 meta 供排查，仅重置 pipeline_status）
        if ($cleanFailed) {
            $permBefore = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key='_xzd_ai_permanent_fail'"
            );
            // 只清理 30 天前的永久失败标记
            $wpdb->query(
                "DELETE pm FROM {$wpdb->postmeta} pm
                 INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                 WHERE pm.meta_key = '_xzd_ai_permanent_fail'
                 AND p.post_modified < DATE_SUB(NOW(), INTERVAL 30 DAY)"
            );
            $permAfter = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key='_xzd_ai_permanent_fail'"
            );
            $results['permanent_fail_cleaned'] = $permBefore - $permAfter;
        }

        // 5. 清理后状态
        $asPendingAfter = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='xzd_worker_process' AND status='pending'"
        );
        $failedAfterFinal = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook='xzd_worker_process' AND status='failed'"
        );

        $totalCleaned = array_sum($results);

        \XZD\AI\V5\Core\Logger::info('health_cleanup', "一键清理完成: 共清理{$totalCleaned}项", $results);

        return $this->success([
            'cleaned'   => $results,
            'total'     => $totalCleaned,
            'after'     => [
                'as_pending' => $asPendingAfter,
                'failed'     => $failedAfterFinal,
            ],
            'message'   => $totalCleaned > 0
                ? "清理完成！共处理 {$totalCleaned} 项：{$results['failed_cleaned']} 条失败任务，{$results['zombies_cleaned']} 个僵尸Runner，{$results['stale_claims_cleaned']} 个过期Claim，{$results['permanent_fail_cleaned']} 个旧永久失败标记。当前队列：{$asPendingAfter} 条待处理。"
                : '没有需要清理的项目，系统状态良好',
        ]);
    }

    private function getPluginTables(): array
    {
        global $wpdb;
        $prefix = $wpdb->prefix;
        $tables = [
            'chat_sessions',
            'chat_messages',
            'chat_stream_chunks',
            'knowledge',
            'knowledge_chunks',
            'faq',
            'intent_cases',
            'automation_rules',
            'automation_logs',
            'operation_log',
            'cost_log',
            'queue',
            'tag_index',
            'logs',
            'write_plans',
            'write_articles',
        ];

        $results = [];
        foreach ($tables as $table) {
            $fullName = $prefix . 'xzd_ai_' . $table;
            $results[$table] = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
                    DB_NAME,
                    $fullName
                )
            ) > 0;
        }

        return $results;
    }
}
