<?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');
    }

    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"),
            ],
        ]);
    }

    /**
     * GET /stats/dashboard — 仪表盘图表数据
     */
    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,
        ]);
    }

    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;
    }
}
