<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\BlogSeo\Http;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SeoController
{
    /**
     * GEO：/llms.txt — 面向 LLM 的站点索引
     */
    public function llmsTxt()
    {
        $siteName = blog_setting('site_name', config('blog.name'));
        $siteDescription = blog_setting('site_description', config('blog.description'));

        $posts = Post::published()->latest('published_at')->limit(200)->get();

        $lines = [];
        $lines[] = '# '.$siteName;
        $lines[] = '';
        $lines[] = '> '.$siteDescription;
        $lines[] = '';
        $lines[] = '## 文章（Markdown 全文可访问 /posts/{slug}.md）';
        $lines[] = '';

        foreach ($posts as $post) {
            $lines[] = '- ['.$post->title.']('.route('posts.show', $post->slug ?: $post->id).') — '.Str::limit(strip_tags($post->excerpt_or_fallback), 120);
        }

        return response(implode("\n", $lines)."\n")
            ->header('Content-Type', 'text/plain; charset=utf-8');
    }

    /**
     * GEO：/posts/{slug}.md — 面向 AI 爬虫的纯 Markdown 导出
     */
    public function postMarkdown(Request $request, string $slug)
    {
        $post = Post::query()->where('slug', $slug)->firstOrFail();

        if ($post->status !== 'published') {
            abort(404);
        }

        $body = $post->content_format === 'markdown' ? $post->content : $this->htmlToMarkdown($post->content);

        $out = "# {$post->title}\n\n";
        if ($post->excerpt) {
            $out .= '> '.$post->excerpt."\n\n";
        }
        $out .= $body."\n";

        return response($out)->header('Content-Type', 'text/markdown; charset=utf-8');
    }

    private function htmlToMarkdown(string $html): string
    {
        $converter = new \League\HTMLToMarkdown\HtmlConverter([
            'strip_tags' => false,
            'hard_break' => true,
        ]);

        return $converter->convert($html);
    }
}
