<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\AiModeration\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;

use App\Blog\Jobs\AiJob;
use App\Blog\Services\LlmClient;
use App\Models\Post;

class AiPolishContentJob implements AiJob, ShouldQueue
{
    use Queueable;

    public function __construct(public int $postId)
    {
    }

    public function handle(LlmClient $llm): void
    {
        $post = Post::find($this->postId);

        if (! $post) {
            return;
        }

        $source = $post->content_format === 'markdown'
            ? $post->content
            : (new \League\HTMLToMarkdown\HtmlConverter())->convert($post->content);

        $polished = $llm->chat([
            ['role' => 'system', 'content' => '你是中文博客编辑。润色下面的文章，保持原意、事实、Markdown 结构不变，改进表达、语法、可读性。直接输出润色后的完整 Markdown。'],
            ['role' => 'user', 'content' => $source],
        ], ['max_tokens' => 4000]);

        // 润色结果暂存，后台点击「采纳」时写回
        $post->update(['meta' => array_merge($post->meta ?? [], ['ai_polished' => $polished])]);
    }
}
