<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\AiModeration\Jobs;

use App\Blog\Jobs\AiJob;
use App\Blog\Services\LlmClient;
use App\Blog\Support\WorkermanBroadcaster;
use App\Models\Comment;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class AiModerateCommentJob implements AiJob, ShouldQueue
{
    use Queueable;

    public function __construct(public int $commentId)
    {
    }

    public function handle(LlmClient $llm): void
    {
        $comment = Comment::with('post')->find($this->commentId);

        if (! $comment || $comment->status !== Comment::STATUS_PENDING) {
            return;
        }

        WorkermanBroadcaster::send('ai.moderation.started', ['comment_id' => $this->commentId]);

        $system = (string) blog_setting('ai_moderation_system_prompt', '你是博客评论审核员。判断评论是否包含：广告/垃圾、人身攻击、违法内容、无关灌水。只回复 JSON：{"verdict":"approved|rejected|spam","reason":"简短理由"}');

        try {
            $raw = $llm->chat([
                ['role' => 'system', 'content' => $system],
                ['role' => 'user', 'content' => '文章标题：'.($comment->post?->title ?? '')."\n\n评论内容：\n".$comment->content],
            ], ['max_tokens' => 200]);

            $verdict = $this->parseVerdict($raw);

            $comment->update([
                'status' => $verdict === 'approved' ? Comment::STATUS_PUBLISHED : ($verdict === 'spam' ? Comment::STATUS_SPAM : Comment::STATUS_REJECTED),
                'ai_review' => ['source' => 'llm', 'raw' => $raw, 'reviewed_at' => now()->toIso8601String()],
            ]);

            if ($verdict === 'approved') {
                $comment->post?->increment('comment_count');
            }

            WorkermanBroadcaster::send('ai.moderation.finished', [
                'comment_id' => $this->commentId,
                'verdict' => $verdict,
            ]);
        } catch (\Throwable $e) {
            Log::error('AI 评论审核失败', ['comment' => $this->commentId, 'error' => $e->getMessage()]);
            WorkermanBroadcaster::send('ai.moderation.failed', ['comment_id' => $this->commentId, 'error' => $e->getMessage()]);
        }
    }

    private function parseVerdict(string $raw): string
    {
        if (preg_match('/"verdict"\s*:\s*"(approved|rejected|spam)"/', $raw, $m)) {
            return $m[1];
        }

        return 'rejected';
    }
}
