<?php

namespace XZD\AI\V5\Tools;

/**
 * 站点类型检测器 — 四级检测 + 多标签 + 缓存
 *
 * 检测优先级：主题内置能力 > 独立插件 > 内容分析 > 手动标记
 * 结果缓存24小时（transient），手动标记不参与缓存过期
 */
class SiteTypeDetector
{
    private static ?self $instance = null;

    public const SITE_TYPES = [
        'blog'       => ['label' => '博客/资讯', 'icon' => '📝'],
        'shop'       => ['label' => '商城/店铺', 'icon' => '🛒'],
        'resource'   => ['label' => '资源/下载', 'icon' => '📦'],
        'forum'      => ['label' => '论坛/社区', 'icon' => '💬'],
        'education'  => ['label' => '教育/课程', 'icon' => '🎓'],
        'news'       => ['label' => '新闻/媒体', 'icon' => '📰'],
        'company'    => ['label' => '企业官网', 'icon' => '🏢'],
        'portfolio'  => ['label' => '作品展示', 'icon' => '🎨'],
        'membership' => ['label' => '会员/订阅', 'icon' => '👑'],
        'general'    => ['label' => '通用站点', 'icon' => '🌐'],
    ];

    private const CACHE_KEY = 'xzd_site_type_detection';
    private const CACHE_TTL = DAY_IN_SECONDS;
    private const MANUAL_KEY = 'xzd_site_type_manual';

    public static function instance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 执行四级检测，返回类型标签数组（按置信度降序）
     *
     * @return array{types: string[], primary: string, details: array, source: string, manual: bool}
     */
    public function detect(): array
    {
        // 检查手动标记
        $manual = get_option(self::MANUAL_KEY, '');
        if (!empty($manual) && isset(self::SITE_TYPES[$manual])) {
            $auto = $this->runDetection();
            return [
                'types'   => array_unique(array_merge([$manual], $auto['types'])),
                'primary' => $manual,
                'details' => $auto['details'],
                'source'  => 'manual',
                'manual'  => true,
            ];
        }

        // 检查缓存
        $cached = get_transient(self::CACHE_KEY);
        if (is_array($cached) && !empty($cached['types'])) {
            return $cached + ['manual' => false];
        }

        $result = $this->runDetection();
        set_transient(self::CACHE_KEY, $result, self::CACHE_TTL);

        return $result + ['manual' => false];
    }

    /**
     * 手动设置站点类型
     */
    public function setManual(string $type): bool
    {
        if (!isset(self::SITE_TYPES[$type])) {
            return false;
        }
        update_option(self::MANUAL_KEY, $type);
        delete_transient(self::CACHE_KEY);
        return true;
    }

    /**
     * 清除手动标记，恢复自动检测
     */
    public function clearManual(): void
    {
        delete_option(self::MANUAL_KEY);
        delete_transient(self::CACHE_KEY);
    }

    /**
     * 获取当前主要类型的标签
     */
    public function getPrimaryLabel(): string
    {
        $result = $this->detect();
        return self::SITE_TYPES[$result['primary']]['label'] ?? '通用站点';
    }

    /**
     * 获取当前主要类型的图标
     */
    public function getPrimaryIcon(): string
    {
        $result = $this->detect();
        return self::SITE_TYPES[$result['primary']]['icon'] ?? '🌐';
    }

    // ===== 内部检测逻辑 =====

    private function runDetection(): array
    {
        $tags = [];
        $details = [];

        // 第一优先级：主题内置能力
        $themeTags = $this->detectThemeCapabilities();
        $tags = array_merge($tags, $themeTags);
        $details['theme'] = $themeTags;

        // 第二优先级：独立插件
        $pluginTags = $this->detectPlugins();
        $tags = array_merge($tags, $pluginTags);
        $details['plugins'] = $pluginTags;

        // 第三优先级：内容分析
        $contentTags = $this->analyzeContent();
        $tags = array_merge($tags, $contentTags);
        $details['content'] = $contentTags;

        // 去重 + 默认
        $tags = array_values(array_unique($tags));
        if (empty($tags)) {
            $tags = ['general'];
        }

        $primary = $tags[0];

        return [
            'types'   => $tags,
            'primary' => $primary,
            'details' => $details,
            'source'  => 'auto',
        ];
    }

    /**
     * 第一优先级：检测主题内置能力（尤其 Zibll）
     */
    private function detectThemeCapabilities(): array
    {
        $tags = [];
        $theme = wp_get_theme();

        // Zibll 主题特殊检测
        if ($theme->get('Template') === 'zibll' || $theme->get_template() === 'zibll' || $theme->get_stylesheet() === 'zibll') {
            // 检测 BBS 论坛功能
            if (post_type_exists('forum_post') || post_type_exists('plate')) {
                $tags[] = 'forum';
            }

            // 检测支付/商城功能
            if (function_exists('zibpay_get_user_balance') || function_exists('zib_get_user_vip_level')) {
                $tags[] = 'shop';
            }

            // 检测 VIP/会员功能
            if (function_exists('zib_get_user_vip_level')) {
                $tags[] = 'membership';
            }

            // 如果没有检测到特定功能，但主题是 Zibll，默认为博客
            if (empty($tags)) {
                $tags[] = 'blog';
            }
        }

        return $tags;
    }

    /**
     * 第二优先级：检测独立插件
     */
    private function detectPlugins(): array
    {
        $tags = [];

        if (class_exists('WooCommerce')) {
            $tags[] = 'shop';
        }
        if (class_exists('Easy_Digital_Downloads')) {
            $tags[] = 'resource';
        }
        if (class_exists('bbPress')) {
            $tags[] = 'forum';
        }
        if (class_exists('LearnPress') || class_exists('Tutor')) {
            $tags[] = 'education';
        }
        if (class_exists('BuddyPress')) {
            $tags[] = 'forum';
        }
        if (class_exists('MemberPress') || class_exists('Paid_Memberships_Pro')) {
            $tags[] = 'membership';
        }

        return $tags;
    }

    /**
     * 第三优先级：内容指纹分析
     */
    private function analyzeContent(): array
    {
        $tags = [];

        $postTypes = get_post_types(['public' => true], 'names');
        $totalPosts = 0;
        $typeCounts = [];

        foreach ($postTypes as $pt) {
            $counts = wp_count_posts($pt);
            if (is_object($counts)) {
                $published = $counts->publish ?? 0;
                if ($published > 0) {
                    $typeCounts[$pt] = $published;
                    $totalPosts += $published;
                }
            }
        }

        if ($totalPosts === 0) {
            $tags[] = 'company'; // 无内容的站点通常是企业站
            return $tags;
        }

        // 产品类 CPT 占比 > 20% → shop
        $productCount = ($typeCounts['product'] ?? 0) + ($typeCounts['shop_product'] ?? 0);
        if ($productCount > 0 && ($productCount / $totalPosts) > 0.2) {
            $tags[] = 'shop';
        }

        // 论坛帖子 CPT
        $forumCount = ($typeCounts['forum_post'] ?? 0) + ($typeCounts['topic'] ?? 0) + ($typeCounts['reply'] ?? 0);
        if ($forumCount > 0 && ($forumCount / $totalPosts) > 0.2) {
            $tags[] = 'forum';
        }

        // 下载类 CPT
        $dlCount = ($typeCounts['download'] ?? 0);
        if ($dlCount > 0 && ($dlCount / $totalPosts) > 0.1) {
            $tags[] = 'resource';
        }

        // 文章（post）多 → 博客/资讯
        $postCount = $typeCounts['post'] ?? 0;
        if ($postCount / $totalPosts > 0.5) {
            $tags[] = 'blog';
        }

        // 页面多 → 企业站
        $pageCount = $typeCounts['page'] ?? 0;
        if ($pageCount > $postCount && $pageCount > 5) {
            $tags[] = 'company';
        }

        // 检查发布频率（最近30天 > 30篇 → 新闻/媒体）
        global $wpdb;
        $recent = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' AND post_date > DATE_SUB(NOW(), INTERVAL 30 DAY)"
        );
        if ($recent > 30) {
            $tags[] = 'news';
        }

        return $tags;
    }

    /**
     * 刷新缓存
     */
    public function refresh(): array
    {
        delete_transient(self::CACHE_KEY);
        return $this->detect();
    }
}
