<?php

namespace XZD\AI\V5\Universal;

/**
 * LLMSTxtGenerator — 生成 llms.txt 文件
 *
 * 为 AI 爬虫提供结构化网站内容索引
 * 规范参考：https://llmstxt.org/
 *
 * @since V3.2.0
 */
class LLMSTxtGenerator
{
    const SLUG = 'llms.txt';

    public function init(): void
    {
        add_action('template_redirect', [$this, 'handle']);
    }

    public function handle(): void
    {
        $path = trim(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH), '/');
        if ($path !== self::SLUG) return;

        header('Content-Type: text/plain; charset=utf-8');
        echo '# ' . get_bloginfo('name') . "\n";
        echo '# ' . get_bloginfo('description') . "\n\n";

        echo '## 最新文章' . "\n\n";
        $posts = get_posts([
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => 20,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);

        foreach ($posts as $post) {
            $summary = get_post_meta($post->ID, '_xzd_ai_summary', true) ?: wp_trim_words(wp_strip_all_tags($post->post_excerpt ?: $post->post_content), 30, '');
            echo '- [' . esc_html($post->post_title) . '](' . get_permalink($post) . ")\n";
            if ($summary) echo '  ' . esc_html($summary) . "\n";
        }

        echo "\n## 分类\n\n";
        $cats = get_categories(['hide_empty' => true, 'number' => 20]);
        foreach ($cats as $cat) {
            echo '- [' . esc_html($cat->name) . '](' . get_category_link($cat) . ') - ' . $cat->count . "篇文章\n";
        }

        echo "\n## 更多\n";
        echo '- Sitemap: ' . home_url('/sitemap.xml') . "\n";
        echo '- RSS: ' . get_bloginfo('rss2_url') . "\n";
        exit;
    }
}
