// services/comment-writer.service.ts
import {Injectable, Logger} from '@nestjs/common';
import {AIProviderFactory} from '../providers/ai-provider.factory';
import {GenerateCommentDto} from '../dto/generate-comment.dto';
import {buildCommentPrompt} from '../prompts/comment.templates';
import {ProviderRouterService} from "./provider-router.service";

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

    constructor(
        private factory: AIProviderFactory,
        private router: ProviderRouterService,
    ) {
    }

    async generateComment(dto: GenerateCommentDto) {
        const decision = this.router.route({
            language: dto.language,
            contentType: 'comment',
            tone: dto.tone,
        });


        // GPT-4o-mini là best choice cho comment đa ngôn ngữ
        // const provider = this.factory.get('openai');

        const provider = this.factory.get(decision.writer);
        this.logger.log(`==> Comment routing: ${decision.reason} ==>`);
        // console.log({dto})
        const {system, user} = buildCommentPrompt({
            originalPost: dto.originalPost,
            angle: dto.angle,
            language: dto.language,
            persona: dto.persona,
            tone: dto.tone,
        });

        // console.log({system, user})

        const res = await provider.complete(
            [
                {role: 'system', content: system},
                {role: 'user', content: user},
            ],
            {
                temperature: 0.9, // cao hơn để tự nhiên
                maxTokens: 150,   // comment ngắn
            },
        );

        // console.log({res});

        // Clean output: bỏ quotes nếu AI lỡ wrap
        const cleaned = res.content.replace(/^["""']|["""']$/g, '').trim();

        return {
            comment: cleaned,
            tokensUsed: res.tokensUsed,
            model: res.model,
            language: dto.language,
        };
    }

    /**
     * Generate nhiều variant để bạn chọn
     */
    // async generateVariants(dto: GenerateCommentDto, count = 3) {
    //     const tasks = Array.from({length: count}, () => this.generateComment(dto));
    //     return Promise.all(tasks);
    // }
}
