<?php

declare(strict_types=1);


namespace App\Console\Commands;

use App\Models\Post;
use Illuminate\Console\Command;
use League\HTMLToMarkdown\HtmlConverter;

class ConvertContent extends Command
{
    protected $signature = 'content:convert
        {--all : 转换全部 html 文章}
        {id? : 单篇文章 ID}
        {--dry-run : 只预览不写库}';

    protected $description = '把文章内容从 HTML 转换为 Markdown（老 sablog 数据迁移用）';

    public function handle(): int
    {
        $query = Post::query()->where('content_format', 'html');

        if ($id = $this->argument('id')) {
            $query->where('id', $id);
        } elseif (! $this->option('all')) {
            $this->error('请指定文章 ID 或使用 --all');

            return self::FAILURE;
        }

        $converter = new HtmlConverter([
            'strip_tags' => false,
            'hard_break' => true,
        ]);

        $renderer = app(\App\Blog\Services\PostContentRenderer::class);

        $posts = $query->get();
        if ($posts->isEmpty()) {
            $this->info('没有需要转换的 HTML 文章');

            return self::SUCCESS;
        }

        $bar = $this->output->createProgressBar($posts->count());
        $bar->start();

        foreach ($posts as $post) {
            // [attach=xx] 是 markdown 保留字符，先换成令牌，渲染时再解析
            $markdown = $converter->convert($renderer->toMarkdownSafeTokens($post->content));

            if ($this->option('dry-run')) {
                $this->newLine();
                $this->line("[{$post->id}] {$post->title}");
                $this->line(mb_substr($markdown, 0, 200));
                $bar->advance();
                continue;
            }

            $post->content = $markdown;
            $post->content_format = 'markdown';
            $post->save();

            $bar->advance();
        }

        $bar->finish();
        $this->newLine();
        $this->info('转换完成：'.($this->option('dry-run') ? '预览模式，未写库' : $posts->count().' 篇已转换为 Markdown'));

        return self::SUCCESS;
    }
}
