// src/modules/writer/facebook.processor.ts
import {InjectQueue, OnWorkerEvent, Processor, WorkerHost} from '@nestjs/bullmq';
import {Job, Queue} from 'bullmq';
import {AIService} from '../../shared/ai.service';
import {PgPostService} from "../../shared/pg.post.service";
import {isEmpty} from "lodash";
import {ContentWriterService} from "./content-writer.service";
import {GenerateContentDto} from "./dto/generate-content.dto";
import {PostCreateInput} from "../../generated/prisma/models/Post";
import {InjectBot} from "nestjs-telegraf";
import {Context, Telegraf} from "telegraf";
import {StyleDetectorService} from "./services/style-detector.service";
import {ContentStyle} from "./enum/style.enum";
import {ContentTone} from "./enum/tone.enum";
import {XStrategy} from "../social-api/x-router.service";
import {SqsPostService} from "../sqs-module/sqs.post.service";

@Processor('content_writer_queue')
export class ContentWriterProcessor extends WorkerHost {
    constructor(
        private aiService: AIService,
        private readonly writerService: ContentWriterService,
        private readonly styleDetectorService: StyleDetectorService,
        private readonly pgPostService: PgPostService,
        @InjectBot() private readonly bot: Telegraf<Context>,
        // private readonly managerService: ManagerService,
        @InjectQueue('content_writer_completed_queue') private readonly fbContentCompletedQueue: Queue,
        private readonly sqsPostService: SqsPostService,
    ) {
        super();
    }

    async process(job: Job<any>): Promise<any> {
        const {title, summary, style, language, tone, enableReview, postLength, autoPublish, telegramChatId} = job.data;
        const topic = summary || title;
        let pgPostCreateDto!: PostCreateInput;

        console.log(`ContentWriterProcessor_processing_${job.name}`);
        let isAutoPublish = false;
        switch (job.name) {
            case 'generate_post_ver2': {
                const dto: GenerateContentDto = {
                    topic,
                    enableReview,
                    language,
                    tone,
                    postLength
                }
                const aiWriterResult = await this.writerService.generate(dto, false, 'openai', 'deepseek');
                // console.log({aiWriterResult});
                pgPostCreateDto = {
                    title: aiWriterResult.topic,
                    content: aiWriterResult.final,
                    style: aiWriterResult.detectedStyle,
                    status: 'pending',
                    prompt: aiWriterResult.prompt,
                    draft: aiWriterResult.draft,
                    tokensUsed: aiWriterResult.tokensUsed,
                    tone: aiWriterResult.detectedTone,
                    model: aiWriterResult.model,
                }
                break;
            }
            case 'generate_post_ver1': {
                const aiWriterResult = await this.aiService.generateContentViaDeepseek(
                    summary || title,
                    style,
                    language
                );

                pgPostCreateDto = {
                    title: aiWriterResult.topic,
                    content: aiWriterResult.final,
                    style: aiWriterResult.detectedStyle,
                    status: 'pending',
                    prompt: aiWriterResult.prompt,
                    tone: aiWriterResult.detectedTone,
                    model: aiWriterResult.model,
                }
                break;
            }

            case 'generate_post_telegram': {
                isAutoPublish = true;
                const topicLen = topic.length;
                console.log({topicLen});
                const dto: GenerateContentDto = {
                    topic,
                    enableReview,
                    language: this.styleDetectorService.detectLanguageFromTelegramAutoContent(topic),
                    tone: topicLen < 150 ? ContentTone.URGENT : tone,
                    postLength,
                    style: topicLen < 150 ? ContentStyle.BREAKING_NEWS : style
                }
                const aiWriterResult = await this.writerService.generate(dto, false);
                // console.log({aiWriterResult});
                pgPostCreateDto = {
                    title: aiWriterResult.topic,
                    content: aiWriterResult.final,
                    style: aiWriterResult.detectedStyle,
                    status: 'pending',
                    prompt: aiWriterResult.prompt,
                    draft: aiWriterResult.draft,
                    tokensUsed: aiWriterResult.tokensUsed,
                    tone: aiWriterResult.detectedTone,
                    model: aiWriterResult.model,
                }
                break;
            }
            case 'generate_post_telegram_batch': {
                isAutoPublish = true;
                // return ;
                const {messages} = job.data;
                let compose_topic = `Viết 1 thread Twitter/X ngắn gọn tổng hợp ${messages.length} tin sau:\n`
                compose_topic += messages.map(m => '- ' + m.text).join('\n');
                const topicLen = compose_topic.length;
                console.log({compose_topic});
                const dto: GenerateContentDto = {
                    topic: compose_topic,
                    enableReview: false,
                    language: this.styleDetectorService.detectLanguageFromTelegramAutoContent(compose_topic),
                    tone: ContentTone.CASUAL,
                    postLength,
                    style: ContentStyle.BREAKING_NEWS
                }
                const aiWriterResult = await this.writerService.generate(dto, false);
                // console.log({aiWriterResult});
                pgPostCreateDto = {
                    title: aiWriterResult.topic,
                    content: aiWriterResult.final,
                    style: aiWriterResult.detectedStyle,
                    status: 'pending',
                    prompt: aiWriterResult.prompt,
                    draft: aiWriterResult.draft,
                    tokensUsed: aiWriterResult.tokensUsed,
                    tone: aiWriterResult.detectedTone,
                    model: aiWriterResult.model,
                }
                break;
            }
            default: {
                break;
            }
        }

        console.log({pgPostCreateDto});

        if (isEmpty(pgPostCreateDto)) {
            return {
                id: 0,
                topic,
                'status': 'error',
            }
        }

        //
        // 2. Giả lập việc tạo ảnh hoặc tìm ảnh minh họa (có thể tích hợp API sau)
        // const imageSuggestion = `https://image-service.com/search?q=${keywords[0]}`;
        //

        // let finalContent = aiWriterResult.content;
        const post = await this.pgPostService.createPost(pgPostCreateDto);
        if (!isAutoPublish) {
            await this.fbContentCompletedQueue.add('generate_post_completed', {
                id: post.id,
                name: 'generate_post_completed',
                needConfirm: 1,
                content: pgPostCreateDto.content,
                autoPublish: false,
                telegramChatId,
                xSubmitProvider: post.id % 2 === 0 ? XStrategy.BROWSER_ONLY : XStrategy.API_ONLY, //cứ 3post api, có 1 post browser

            }, {attempts: 1, backoff: 5000, removeOnComplete: true,});
        } else {
            await this.sqsPostService.postFlashKaze({
                id: post.id,
                name: 'generate_post_completed',
                type: 'X_POSTER_TWEET',
                needConfirm: 1,
                content: pgPostCreateDto.content,
                autoPublish,
                telegramChatId,
                publishTo: ['x', 'fb'],
                xSubmitProvider: post.id % 3 === 0 ? XStrategy.API_FIRST : XStrategy.BROWSER_ONLY, //cứ 3post api, có 1 post browser
            })
        }
        return {
            id: post.id,
            // content: postContent,
            //image: imageSuggestion,
            status: 'ready_to_post',
            telegramChatId,
        };
    }

    @OnWorkerEvent('completed')
    async onCompleted(job: Job<any>) {
        console.log('ContentWriterProcessor_completed');
        const adminChatId = process.env.TELEGRAM_ADMIN_ID || 0;
        const postId = job.returnvalue.id;
        const telegramChatId = job.returnvalue.telegramChatId;
        if (postId === 0) {
            const topic = job.returnvalue.topic;

            await this.bot.telegram.sendMessage(telegramChatId || adminChatId, `Lỗi viết bài: ${topic}`);
        } else {
            //return job.returnvalue.topic;
        }
    }

}
