<?php

namespace XZD\AI\V5\Agents;

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

    /**
     * 获取完整网站画像
     *
     * @return array
     */
    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;
    }

    /**
     * 生成注入提示词的文本描述
     *
     * @return string
     */
    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']} 次",
        ];

        // V3.2: 注入站点业务画像（由学习引擎自动生成）
        $profile = $this->getSiteBusinessProfile();
        if ($profile) {
            $lines[] = '';
            $lines[] = '--- 站点业务画像 ---';
            $lines[] = $profile;
        }

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

    /**
     * V3.2: 从知识库获取站点业务画像
     */
    private function getSiteBusinessProfile(): string
    {
        global $wpdb;
        $siteName = get_bloginfo('name');
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT content FROM {$wpdb->prefix}xzd_ai_knowledge
             WHERE title LIKE %s AND source_type='system' AND status='active'
             LIMIT 1",
            $siteName . '%业务画像'
        ));
        return $row ? $row->content : '';
    }

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

    // 内部

    /**
     * 获取站点基本信息
     *
     * @return array
     */
    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'),
        ];
    }

    /**
     * 获取内容统计
     *
     * @return array
     */
    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,
        ];
    }

    /**
     * 获取用户统计
     *
     * @return array
     */
    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),
        ];
    }

    /**
     * 获取主题信息
     *
     * @return array
     */
    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,
        ];
    }

    /**
     * 获取活跃插件列表
     *
     * @return array
     */
    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,
        ];
    }

    /**
     * 获取AI统计
     *
     * @return array
     */
    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,
        ];
    }
}
