<?php

namespace XZD\AI\V5\Agents;

/**
 * 网站画像 — 收集 WordPress 站点上下文信息
 *
 * 注入到每个 Agent 的系统提示词中，使 AI 了解当前网站状态
 */
class SiteProfile
{
    private array $cache = [];
    private bool $loaded = false;

    /**
     * 获取完整网站画像
     */
    public function getProfile(): array
    {
        if ($this->loaded) {
            return $this->cache;
        }

        $this->cache = [
            'site'     => $this->getSiteInfo(),
            'content'  => $this->getContentStats(),
            'users'    => $this->getUserStats(),
            'theme'    => $this->getThemeInfo(),
            'plugins'  => $this->getActivePlugins(),
            'ai'       => $this->getAIStats(),
        ];

        $this->loaded = true;
        return $this->cache;
    }

    /**
     * 生成注入提示词的文本描述
     */
    public function toPromptText(): string
    {
        $p = $this->getProfile();
        $lines = [
            "网站名称: {$p['site']['name']}",
            "网站地址: {$p['site']['url']}",
            "网站描述: {$p['site']['description']}",
            "文章总数: {$p['content']['total_posts']}",
            "页面总数: {$p['content']['total_pages']}",
            "分类数: {$p['content']['total_categories']}",
            "标签数: {$p['content']['total_tags']}",
            "评论总数: {$p['content']['total_comments']}",
            "用户总数: {$p['users']['total_users']}",
            "管理员数: {$p['users']['total_admins']}",
            "当前主题: {$p['theme']['name']} (v{$p['theme']['version']})",
            "活跃插件数: {$p['plugins']['count']}",
            "AI 已处理文章: {$p['ai']['total_ai_calls']} 次",
        ];

        return implode("\n", $lines);
    }

    /**
     * 刷新缓存
     */
    public function refresh(): self
    {
        $this->loaded = false;
        $this->cache = [];
        return $this;
    }

    // ===== 内部 =====

    private function getSiteInfo(): array
    {
        return [
            'name'        => get_bloginfo('name'),
            'url'         => home_url(),
            'description' => get_bloginfo('description'),
            'language'    => get_locale(),
            'timezone'    => wp_timezone_string(),
            'version'     => get_bloginfo('version'),
        ];
    }

    private function getContentStats(): array
    {
        $counts = wp_count_posts();
        $publish = $counts->publish ?? 0;
        $draft   = $counts->draft ?? 0;
        $pending = $counts->pending ?? 0;
        $private = $counts->private ?? 0;

        return [
            'total_posts'      => (int) $publish,
            'draft_posts'       => (int) $draft,
            'pending_posts'     => (int) $pending,
            'private_posts'     => (int) $private,
            'total_pages'       => (int) (wp_count_posts('page')->publish ?? 0),
            'total_categories'  => (int) wp_count_terms('category'),
            'total_tags'        => (int) wp_count_terms('post_tag'),
            'total_comments'    => (int) wp_count_comments()->total_comments,
            'pending_comments'  => (int) wp_count_comments()->moderated,
        ];
    }

    private function getUserStats(): array
    {
        $users = count_users();
        return [
            'total_users' => (int) ($users['total_users'] ?? 0),
            'total_admins' => (int) ($users['avail_roles']['administrator'] ?? 0),
            'total_editors' => (int) ($users['avail_roles']['editor'] ?? 0),
            'total_authors' => (int) ($users['avail_roles']['author'] ?? 0),
        ];
    }

    private function getThemeInfo(): array
    {
        $theme = wp_get_theme();
        return [
            'name'       => $theme->get('Name'),
            'version'    => $theme->get('Version'),
            'has_deep_adapter' => \XZD\AI\V5\Theme\AdapterRegistry::isZibll(),
            'dark_mode'  => false,
        ];
    }

    private function getActivePlugins(): array
    {
        $all = get_option('active_plugins', []);
        $names = [];
        foreach ($all as $plugin) {
            $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
            $names[] = $data['Name'] ?? basename($plugin);
        }

        return [
            'count'   => count($names),
            'plugins' => $names,
        ];
    }

    private function getAIStats(): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'xzd_ai_operation_log';

        $totalCalls = 0;
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") === $table) {
            $totalCalls = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table}");
        }

        return [
            'total_ai_calls' => $totalCalls,
        ];
    }
}
