// services/reviewer.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { AIProviderFactory, ProviderName } from '../providers/ai-provider.factory';
import { PromptBuilderService } from './prompt-builder.service';
import { ContentContext } from '../interfaces/content-context.interface';
import {AIMessage} from "../interfaces/ai-provider.interface";

export interface ReviewResult {
    improved: string;
    notes: string;
    tokensUsed: number;
    model: string;
    languageValid: boolean;
    prompt?: AIMessage[];
}

@Injectable()
export class ReviewerService {
    private readonly logger = new Logger(ReviewerService.name);

    constructor(
        private factory: AIProviderFactory,
        private promptBuilder: PromptBuilderService,
    ) {}

    async review(
        draft: string,
        ctx: ContentContext,
        providerName: ProviderName = 'deepseek',
        originalTopic:string,
        maxToken:number// rẻ nhất cho review
    ): Promise<ReviewResult> {
        console.log('==> ReviewerService_review: ');
        const provider = this.factory.get(providerName);
        const messages = this.promptBuilder.buildReviewerMessages(draft, ctx);
        console.log('==> ReviewerService_review_promp:==> ');

        const res = await provider.complete(messages, { temperature: 0.3, maxTokens: maxToken });

        // Parse JSON an toàn
        const parsed = this.safeParseJson(res.content);
        return {
            improved: parsed?.improved ?? draft,
            notes: parsed?.notes ?? '',
            tokensUsed: res.tokensUsed,
            model: res.model,
            prompt: messages,
            languageValid: true,
        };
    }

    private safeParseJson(text: string): { improved?: string; notes?: string } | null {
        try {
            const match = text.match(/\{[\s\S]*\}/);
            if (!match) return null;
            return JSON.parse(match[0]);
        } catch (e) {
            this.logger.warn('Reviewer returned non-JSON output');
            return null;
        }
    }
}
