import {
    Body,
    Controller,
    Delete,
    Get,
    Param,
    Post,
    Put,
    Query,
    UseGuards,
    Request,
    Patch,
    UseInterceptors,
    UploadedFile,
    Res,
} from '@nestjs/common';
// import { AuthGuard } from 'src/auth/auth.guard';
import * as Multer from 'multer';

import { ApiBearerAuth, ApiTags, ApiOperation, ApiConsumes, ApiBody } from '@nestjs/swagger';
import * as dto from './dto/index';
import { KnowledgeService } from './knowledge.service';
import { AuthGuard } from '../auth/auth.guard';
// import { RolesGuard } from 'src/auth/roles.guard';
import { CallService } from '../call/call.service';
import { FileInterceptor } from '@nestjs/platform-express';
@ApiTags('knowledge-base')
@Controller('knowledge-base')
export class KnowledgeController {
    constructor(private readonly KnowledgeService: KnowledgeService,
        private readonly CallService: CallService
    ) { }



    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Post()
    async knowledge_base(@Body() body: dto.Knowledge.knowledgeBaseCreate, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.knowledge_base_create(body, req)
            return res
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Get()
    async knowledge_base_list(@Query() body: dto.Knowledge.getKnowledgeBase, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.knowledge_base_get(body, req)
            return res
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Get("/:_id")
    async knowledge_base_detail(@Param("_id") knowledge_base_id: string, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.knowledge_base_detail(knowledge_base_id, req)
            return res
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Get("/:_id/documents")
    async knowledge_base_documents(@Param("_id") knowledge_base_id: string, @Query() body: dto.Knowledge.getKnowledgeBaseDocument, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.knowledge_base_documents(knowledge_base_id, body, req)
            return res
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Delete("/documents/:_id")
    async documents_delete(@Param("_id") document_id: string, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.document_delete(document_id, req)
            return res
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Delete("/:_id")
    async knowledge_base_delete(@Param("_id") knowledge_base_id: string, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.knowledge_base_delete(knowledge_base_id, req)
            return res
        } catch (error) {
            throw error
        }
    }


    // @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @ApiConsumes('multipart/form-data')
    @ApiBody({ type: dto.Knowledge.Upload })
    @UseInterceptors(FileInterceptor('file'))
    @Post("pdf-upload")
    async pdfUpload(@UploadedFile() file: Multer.file, @Body() body: dto.Knowledge.Upload, @Request() req: any) {
        try {
            let { knowledge_base_id } = req.body
            knowledge_base_id = body?.knowledge_base_id ? body?.knowledge_base_id : knowledge_base_id ? knowledge_base_id : null

            let res = await this.KnowledgeService.pdfUpload(file, knowledge_base_id)
            return {
                message: 'Document processed successfully',
                chunks: res.length,
            };
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Post("text-upload")
    async textUpload(@Body() body: dto.Knowledge.AddTextDto, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.textUpload(body?.text, body?.title, body?.knowledge_base_id)
            return res
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Post("url-upload")
    async scrapAndUpload(@Body() body: dto.Knowledge.urlUpload) {
        try {
            let res = await this.KnowledgeService.scrapAndUpload(body?.url, body?.title, body?.knowledge_base_id, body?.depth)
            return {
                message: 'Document processed successfully',
                // chunks: res.length,
                res
            };
        } catch (error) {
            throw error
        }
    }

    @UseGuards(AuthGuard)
    @ApiBearerAuth('authorization')
    @Get("get-answer/data")
    async getAnswer(@Query() body: dto.Knowledge.getAnswer) {
        try {
            try {
                console.time('Total time');
                let data = await this.KnowledgeService.getAnswer(body?.query, body?.chat_history, body?.agent_id)
                console.timeEnd('Total time');
                return data
            } catch (error) {
                throw error
            }
        } catch (error) {
            throw error
        }
    }

    @Post("landing/page/ai")
    async getLandingPageAnswer(@Body() body: dto.Knowledge.getLandingAnswer, @Res() res: any) {
        try {
            try {
                console.time('Total time');
                let data = await this.KnowledgeService.getAnswerForLandingPage(body)
                // console.log("data", data?.data);

                res.set({
                    // 'Content-Type': 'audio/mpeg', // Assuming the response is MP3 format
                    'Content-Type': 'application/json',
                    // 'Content-Disposition': 'inline; filename="synthesized-audio.mp3"', // Optional
                    'X-Chat-ID': data?.chat_id
                });
                res.send({
                    data: data?.data,
                    chat_id: data?.chat_id,
                    model_text: data?.model_text
                });

                console.timeEnd('Total time');
                // return data
            } catch (error) {
                throw error
            }
        } catch (error) {
            throw error
        }
    }

    @Post("landing/page/ai/2")
    async getLandingPageAnswerV2(@Body() body: dto.Knowledge.getLandingAnswer, @Res() res: any) {
        try {
            try {
                console.time('Total time');
                let data = await this.KnowledgeService.getAnswerForLandingPageV2(body)

                res.set({
                    'Content-Type': 'audio/mpeg', // Assuming the response is MP3 format
                    'Content-Disposition': 'inline; filename="synthesized-audio.mp3"', // Optional
                });
                res.send(data?.data);

                console.timeEnd('Total time');
            } catch (error) {
                throw error
            }
        } catch (error) {
            throw error
        }
    }

    // @UseGuards(AuthGuard)
    // @ApiBearerAuth('authorization')
    @Post("landing-page-knowledge-base")
    async textUploadDefault(@Body() body: dto.Knowledge.urlUpload, @Request() req: any) {
        try {
            let res = await this.KnowledgeService.knowledgeBaseUploadLandingPage(body?.url)
            return res
        } catch (error) {
            throw error
        }
    }

}
