<?php

namespace XZD\AI\V5\Universal;

/**
 * SEOBridge — 检测专业SEO插件并桥接AI生成的SEO数据
 *
 * 检测顺序: Rank Math > Yoast > SEOPress > AIOSEO
 * 找到专业插件 → 将 _xzd_ai_seo_* 数据写入对应插件的字段
 * 没找到 → 插件自己的 MetaRenderer 输出
 *
 * @since V3.3.0
 */
class SEOBridge
{
    private static ?string $detected = null;
    private static bool $checked = false;

    /**
     * 检测到的SEO插件类型（供外部查询）
     */
    public static function detected(): ?string
    {
        self::check();
        return self::$detected;
    }

    /**
     * 是否已被专业SEO插件接管输出
     */
    public static function isTakenOver(): bool
    {
        self::check();
        return self::$detected !== null;
    }

    /**
     * 将AI生成的SEO数据写入文章
     * 有专业插件 → 写其字段；无 → 写我们自己的 post_meta（MetaRenderer 读取）
     */
    public static function writeSEOData(int $postId, string $title, string $keywords, string $description): void
    {
        self::check();

        // 始终保存到我们自己的字段（多插件场景兼容）
        if ($title) update_post_meta($postId, '_xzd_ai_seo_title', $title);
        if ($keywords) update_post_meta($postId, '_xzd_ai_seo_keywords', $keywords);
        if ($description) update_post_meta($postId, '_xzd_ai_seo_description', $description);

        // 同步到专业插件字段
        switch (self::$detected) {
            case 'rankmath':
                if ($title) update_post_meta($postId, 'rank_math_title', $title);
                if ($description) update_post_meta($postId, 'rank_math_description', $description);
                if ($keywords) update_post_meta($postId, 'rank_math_focus_keyword', $keywords);
                break;
            case 'yoast':
                if ($title) update_post_meta($postId, '_yoast_wpseo_title', $title);
                if ($description) update_post_meta($postId, '_yoast_wpseo_metadesc', $description);
                if ($keywords) update_post_meta($postId, '_yoast_wpseo_focuskw', $keywords);
                break;
            case 'seopress':
                if ($title) update_post_meta($postId, '_seopress_titles_title', $title);
                if ($description) update_post_meta($postId, '_seopress_titles_desc', $description);
                // SEOPress 不支持独立的 keywords 字段，存到我们的字段即可
                break;
            case 'aioseo':
                if ($title) update_post_meta($postId, '_aioseo_title', $title);
                if ($description) update_post_meta($postId, '_aioseo_description', $description);
                if ($keywords) update_post_meta($postId, '_aioseo_keywords', $keywords);
                break;
            case 'zibll':
                // Zibll 主题通过 zib_get_post_meta() 读取 zib_other_data 中的 title/keywords/description
                $zibData = get_post_meta($postId, 'zib_other_data', true);
                if (!is_array($zibData)) $zibData = [];
                if ($title) $zibData['title'] = $title;
                if ($keywords) $zibData['keywords'] = $keywords;
                if ($description) $zibData['description'] = $description;
                update_post_meta($postId, 'zib_other_data', $zibData);
                break;
        }
    }

    /**
     * 检测已安装并激活的专业SEO插件或主题自带SEO
     */
    private static function check(): void
    {
        if (self::$checked) return;
        self::$checked = true;

        // Rank Math
        if (class_exists('RankMath') || defined('RANK_MATH_VERSION')) {
            self::$detected = 'rankmath';
            return;
        }
        // Yoast SEO
        if (class_exists('WPSEO_Options') || defined('WPSEO_VERSION')) {
            self::$detected = 'yoast';
            return;
        }
        // SEOPress
        if (defined('SEOPRESS_VERSION') || function_exists('seopress_get_service')) {
            self::$detected = 'seopress';
            return;
        }
        // All in One SEO
        if (defined('AIOSEO_VERSION') || function_exists('aioseo')) {
            self::$detected = 'aioseo';
            return;
        }
        // Zibll 主题自带SEO（zib_seo() 输出在 wp_head priority 1）
        $theme = wp_get_theme();
        $template = $theme->get_template() ?: $theme->get_stylesheet();
        if ($template === 'zibll') {
            self::$detected = 'zibll';
            return;
        }
    }
}
