<?php

namespace XZD\AI\V5\Universal;

/**
 * MetaRenderer — SEO 前端输出层（精简版）
 *
 * 只输出 AI 生成的 title / description / keywords 三个 meta 标签。
 * 不输出 Schema / OG / Twitter Card / Sitemap 等。
 *
 * 如果 SEOBridge 检测到其他专业 SEO 插件已接管，则不输出（让专业插件处理）。
 *
 * @since V3.2.0
 */
class MetaRenderer
{
    private static bool $rendered = false;

    /**
     * 注册 Hook
     */
    public function init(): void
    {
        add_action('wp_head', [$this, 'renderAll'], 1);
        add_filter('get_canonical_url', [$this, 'filterCanonical'], 10, 2);
    }

    /**
     * 检查是否被专业 SEO 插件接管
     */
    private function isOverridden(): bool
    {
        return class_exists(SEOBridge::class) && SEOBridge::isTakenOver();
    }

    /**
     * 主渲染入口
     */
    public function renderAll(): void
    {
        if (self::$rendered) return;
        if ($this->isOverridden()) return; // 专业 SEO 插件已接管，不输出
        self::$rendered = true;

        if (is_singular()) {
            $postId = get_the_ID();
            if ($postId) {
                $this->renderTitle($postId);
                $this->renderDescription($postId);
                $this->renderKeywords($postId);
            }
        }

        if (is_home() || is_front_page()) {
            $desc = get_bloginfo('description');
            if ($desc) printf('<meta name="description" content="%s">' . "\n", esc_attr($desc));
        }
    }

    private function renderTitle(int $postId): void
    {
        $aiTitle = get_post_meta($postId, '_xzd_ai_seo_title', true);
        if (!empty($aiTitle)) {
            printf('<title>%s</title>' . "\n", esc_html($aiTitle));
        }
    }

    private function renderDescription(int $postId): void
    {
        $desc = get_post_meta($postId, '_xzd_ai_seo_description', true);
        if (empty($desc)) $desc = get_post_meta($postId, '_xzd_ai_summary', true);
        if (empty($desc)) {
            $post = get_post($postId);
            $desc = $post ? wp_trim_words(wp_strip_all_tags($post->post_excerpt ?: $post->post_content), 30, '') : '';
        }
        if (!empty($desc)) {
            printf('<meta name="description" content="%s">' . "\n", esc_attr(mb_substr($desc, 0, 320)));
        }
    }

    private function renderKeywords(int $postId): void
    {
        $kw = get_post_meta($postId, '_xzd_ai_seo_keywords', true);
        if (empty($kw)) {
            $tags = wp_get_post_tags($postId, ['fields' => 'names']);
            $kw = !empty($tags) ? implode(',', array_slice($tags, 0, 10)) : '';
        }
        if (!empty($kw)) {
            printf('<meta name="keywords" content="%s">' . "\n", esc_attr($kw));
        }
    }

    public function filterCanonical(string $canonicalUrl, $post): string
    {
        if (!empty($canonicalUrl)) return $canonicalUrl;
        $postId = is_object($post) ? ($post->ID ?? 0) : (int) $post;
        if (is_singular('post') && $postId) {
            $perm = get_permalink($postId);
            return $perm ?: $canonicalUrl;
        }
        return $canonicalUrl;
    }
}
