import {OnWorkerEvent, Processor, WorkerHost} from "@nestjs/bullmq";
import {Job} from "bullmq";
import {PostCreateInput} from "../../generated/prisma/models/Post";
import {CommentWriterService} from "./services/comment-writer.service";
import {GenerateCommentDto} from "./dto/generate-comment.dto";
import {XReaderService} from "../x-reader/x-reader.service";
import {InjectBot} from "nestjs-telegraf";
import {Context, Telegraf} from "telegraf";
import {Logger} from "@nestjs/common";
import {QuoteWriterService} from "./services/quote-writer.service";
import {GenerateQuoteDto} from "./dto/generate-quote.dto";
import {TextUtil} from "../../common/utils/text.util";
import {isEmpty} from "lodash";


@Processor('comment_writer_queue')
export class CommentWriterProcessor extends WorkerHost {
    private readonly logger = new Logger(CommentWriterProcessor.name);

    constructor(
        private readonly quoteWriterService: QuoteWriterService,
        private readonly commentWriterService: CommentWriterService,
        private readonly xreader: XReaderService,
        @InjectBot() private readonly bot: Telegraf<Context>,
        //@InjectQueue('comment_writer_completed_queue') private readonly aiCommentWriteCompletedQueue: Queue,

    ) {
        super();
    }

    async process(job: Job, token: string | undefined): Promise<any> {

        const {
            title,
            summary,
            style,
            url,
            quoteType,
            quoteText,
            language,
            tone,
            agle,
            comtext,
            telegramChatId,
        } = job.data;
        const topic = summary || title;
        let pgPostCreateDto!: PostCreateInput;

        console.log(`CommentWriterProcessor_processing_${job.name}`);
        switch (job.name) {
            case 'generate_comment_twitter': {

                const xpost = await this.xreader.readXPost(url);

                const dto: GenerateCommentDto = {
                    originalPost: xpost.text,
                    language
                }

                // aiWriterResult={
                //     comment: cleaned,
                //         tokensUsed: res.tokensUsed,
                //     model: res.model,
                //     language: dto.language,
                // }
                // const aiWriterResult = {
                //     comment: "Greet",
                //     url
                // }
                const aiWriterResult = await this.commentWriterService.generateComment(dto);

                this.logger.log({aiWriterResult});

                // await this.aiCommentWriteCompletedQueue.add('generate_comment_completed', {
                //     //id: post.id,
                //     name: 'generate_comment_completed',
                //     needConfirm: 1,
                //     content: aiWriterResult.comment,
                //     url: url,
                // }, {attempts: 1, backoff: 5000, removeOnComplete: true,});

                await this.bot.telegram.sendMessage(telegramChatId, `
                Đã viết reply xong ...\nmodel: ${aiWriterResult.model} - tokenUsed: ${aiWriterResult.tokensUsed}`);
                // const _url = url.indexOf('?s=20') > -1 ? url : `${url}?s=20`;
                // console.log({_url});

                //tìm xem bài này có phải của tôi không
                const X_USERS = process.env.TWITTER_USERNAMES!.split(',');
                console.log({X_USERS});
                const isMyPost = url.indexOf(process.env.TWITTER_USERNAMES) > -1

                //await this.bot.telegram.sendMessage(telegramChatId || adminChatId, isMyPost ? 'Đây là bài của bạn, có thế gửi' : 'Có thế không gửi được')
                await this.bot.telegram.sendMessage(telegramChatId,
                    `${aiWriterResult.comment}`,
                    {
                        parse_mode: 'Markdown',
                        reply_markup: {
                            inline_keyboard: [
                                ...X_USERS.map((xuser) => {
                                    return [{
                                        text: `↗️X ${xuser}`,
                                        callback_data: `publish-reply-twitter1_${xpost.tweetId}_${xuser}`
                                    }];
                                }),
                                [
                                    {text: "🗑️ Hủy bài", callback_data: `delete-reply_${xpost.tweetId}`}
                                ]
                            ]
                        }
                    });

                // 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_comment_as_text_twitter': {
                const {
                    tweetId
                } = job.data;
                const dto: GenerateCommentDto = {
                    originalPost: comtext,
                    language,
                    angle: agle,
                    tone: tone

                }
                const X_USERS = process.env.TWITTER_USERNAMES!.split(',');
                console.log({X_USERS});

                const aiWriterResult = await this.commentWriterService.generateComment(dto);

                this.logger.log({aiWriterResult});


                const adminChatId = process.env.TELEGRAM_ADMIN_ID || 0;
                await this.bot.telegram.sendMessage(telegramChatId || adminChatId, `
                Đã viết reply xong ...\ntweetId=${tweetId}\nmodel: ${aiWriterResult.model} }
                `);

                await this.bot.telegram.sendMessage(telegramChatId || adminChatId,
                    `${aiWriterResult.comment}`,
                    {
                        reply_markup: {
                            inline_keyboard: [
                                ...(!isEmpty(tweetId) ? X_USERS.map((xuser) => {
                                    return [{
                                        text: `↗️X ${xuser}`,
                                        callback_data: `publish-reply-twitter_${tweetId}_${xuser}`
                                    }];
                                }) : [
                                    // {
                                    //     text: `Reply vào bài X`,
                                    //     callback_data: `publish-reply-twitter_${tweetId}_${xuser}`
                                    // }
                                ])
                                ,
                                [
                                    {text: "🗑️ Hủy bài", callback_data: `delete-reply_${tweetId}`}
                                ]
                            ]
                        }
                    });

                // 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_quote_twitter': {
                this.logger.debug('===>generate_quote_twitter:', url);
                const xpost = await this.xreader.readXPost(url);

                const originalAuthor = `${xpost.author} ${xpost.handle}`;
                const dto: GenerateQuoteDto = {
                    originalPost: xpost.text,
                    originalAuthor,
                    language,
                    quoteType,
                    tweetId: xpost.tweetId,
                }
                await this.onHandleAiGenerateQuote(
                    dto,
                    false,
                    telegramChatId,
                );
                // const aiWriterResult = await this.quoteWriterService.generateQuote(dto);
                //
                // this.logger.log({aiWriterResult});
                // const adminChatId = process.env.TELEGRAM_ADMIN_ID || 0;
                // await this.bot.telegram.sendMessage(adminChatId, `
                // Đã viết quote xong ...\nmodel: ${aiWriterResult.model} - type: ${aiWriterResult.quoteType}
                // `);
                // const _url = url.indexOf('?s=') > -1 ? url : `${url}?s=20`;

                //xoá url trong bài vì tốn 0,2$ cho bài có url
                // let isSendSucceeded = true;
                // const quoteCleanUrl = TextUtil.removeAllUrl(dto.originalPost)
                // await this.bot.telegram.sendMessage(
                //     adminChatId,
                //     `${aiWriterResult.quote}\n\nQuote:"${quoteCleanUrl}\n\n${originalAuthor}"`,
                //     {
                //         // parse_mode: 'Markdown',
                //         reply_markup: {
                //             inline_keyboard: [
                //                 [
                //                     {text: "↗️X", callback_data: `publish-quote-twitter_${xpost.tweetId}`},
                //                     {text: "🗑️ Hủy bài", callback_data: `delete-quote_${xpost.tweetId}`}
                //                 ],
                //             ]
                //         }
                //     })
                //     .catch(error => {
                //         console.log('==> send message to telegram error:' + error.message);
                //         console.error(error);
                //         isSendSucceeded = false;
                //     });
                break;
            }
            case 'generate_quote_twitter_as_text_input': {
                const dto: GenerateQuoteDto = {
                    originalPost: quoteText,
                    originalAuthor: '',
                    language,
                    quoteType
                }
                await this.onHandleAiGenerateQuote(
                    dto,
                    false,
                    telegramChatId,
                );
                break;
            }
        }


        return {
            //id: post.id,
            // content: postContent,
            //image: imageSuggestion,
            status: 'ready_to_post'
        };


    }

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

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

    private async onHandleAiGenerateQuote(
        dto: GenerateQuoteDto,
        isAttachQuote = true,
        telegramChatId: number = 0
    ) {
        const aiWriterResult = await this.quoteWriterService.generateQuote(dto);

        this.logger.log({aiWriterResult});
        const sendId = telegramChatId || process.env.TELEGRAM_ADMIN_ID || 0;
        await this.bot.telegram.sendMessage(sendId, `
                Đã viết quote xong ...\nmodel: ${aiWriterResult.model} - type: ${aiWriterResult.quoteType}
                `);

        //
        let finalQuote = aiWriterResult.quote;
        if (isAttachQuote) {
            finalQuote += `\n\nQuote:"${dto.originalPost}\n\n${dto.originalAuthor}`
        }
        //xoá url trong bài vì tốn 0,2$ cho bài có url
        const finalQuoteCleanUrl = TextUtil.removeAllUrl(finalQuote)

        const X_USERS = process.env.TWITTER_USERNAMES!.split(',');

        await this.bot.telegram.sendMessage(
            sendId,
            finalQuoteCleanUrl,
            {
                // parse_mode: 'Markdown',
                reply_markup: {
                    inline_keyboard: [
                        ...X_USERS.map((xuser) => {
                            return [{
                                text: `↗️X ${xuser}`,
                                callback_data: `publish-quote-twitter_${dto.tweetId}_${xuser}`
                            }];
                        }),
                        [
                            {text: "🗑️ Hủy bài", callback_data: `delete-quote_${dto.tweetId}`}
                        ],
                    ]
                }
            })
            .catch(error => {
                console.log('==> send message to telegram error:' + error.message);
                console.error(error);
            });
    }

}
