import { Injectable } from "@nestjs/common";
import * as fs from "fs";
import * as path from "path";
import * as ffmpeg from "fluent-ffmpeg";
import { promisify } from "util";
import axios from "axios";
import * as https from "https";

@Injectable()
export class BhasiniService {
  async create(file: Express.Multer.File) {
    if (!file || !file[0].buffer) {
      throw new Error("File or file buffer is missing");
    }
    const fileBase64 = file[0].buffer.toString("base64");
    // Trim the audio buffer to the first 10 seconds
    const audioBuffer = file[0].buffer;
    const audioType = file[0].mimetype;

    // Use ffmpeg to trim the audio buffer (requires fluent-ffmpeg and a temporary file)

    const writeFile = promisify(fs.writeFile);
    const readFile = promisify(fs.readFile);
    const unlink = promisify(fs.unlink);

    const tempInputPath = path.join(__dirname, "temp_input_" + Date.now());
    const tempOutputPath = path.join(
      __dirname,
      "temp_output_" + Date.now() + ".wav"
    );

    await writeFile(tempInputPath, audioBuffer);

    await new Promise((resolve, reject) => {
      ffmpeg(tempInputPath)
        .setStartTime(0)
        .setDuration(10)
        .output(tempOutputPath)
        .on("end", resolve)
        .on("error", reject)
        .run();
    });

    const trimmedAudioBuffer = await readFile(tempOutputPath);

    await unlink(tempInputPath);
    await unlink(tempOutputPath);
    const trimmedAudioBase64 = trimmedAudioBuffer.toString("base64");

    const ALD_Body = {
      pipelineTasks: [
        {
          taskType: "audio-lang-detection",
          config: {
            serviceId: "bhashini/iitmandi/audio-lang-detection/gpu",
          },
        },
      ],
      inputData: {
        audio: [
          {
            audioContent: trimmedAudioBase64,
          },
        ],
      },
    };
    const headers = {
      "Content-Type": "application/json",
      Authorization:
        "qD1gRCY3htMwe5m1byIXyi_8GTpj39GvJnpWZ_0Sp4fAvjghw1LXWS_uOvYkYr4J",
    };
    try {
      const gheckSourceLanguage = await axios.post(
        `https://dhruva-api.bhashini.gov.in/services/inference/pipeline`,
        ALD_Body,
        { headers }
      );
      console.log(
        gheckSourceLanguage.data?.pipelineResponse[0]?.output[0]
          .langPrediction[0]?.langCode,
        "oikjuhygfd"
      );

      const source_lang =
        gheckSourceLanguage.data?.pipelineResponse[0]?.output[0]
          .langPrediction[0]?.langCode;

      const ASR_NMT_TTS_payload = {
        pipelineTasks: [
          {
            taskType: "asr",
            config: {
              language: {
                sourceLanguage: source_lang,
              },
              serviceId: "ai4bharat/conformer-multilingual-indo_aryan-gpu--t4",
              audioFormat: "flac",
              samplingRate: 16000,
            },
          },
          {
            taskType: "translation",
            config: {
              language: {
                sourceLanguage: source_lang,
                targetLanguage: "en",
              },
              serviceId: "ai4bharat/indictrans-v2-all-gpu--t4",
            },
          },
          {
            taskType: "tts",
            config: {
              language: {
                sourceLanguage: "en",
              },
              serviceId: "ai4bharat/indic-tts-coqui-misc-gpu--t4",
              gender: "female",
              samplingRate: 8000,
            },
          },
        ],
        inputData: {
          audio: [
            {
              audioContent: fileBase64,
            },
          ],
        },
      };

      const ASR_NMT_SourceLanguage = await axios.post(
        `https://dhruva-api.bhashini.gov.in/services/inference/pipeline`,
        ASR_NMT_TTS_payload,
        { headers }
      );

      const target_lang =
        ASR_NMT_SourceLanguage.data?.pipelineResponse[1]?.output[0].target;

      const httpsAgent = new https.Agent({
        rejectUnauthorized: false,
      });

      const transcript_header = {
        "X-API-Key":
          "f1e51d152ee82d6201a347736cb3bd5c80c3135a3001725a63b999c61d384da9",
        "Content-Type": "application/json",
      };

      const payload = {
        transcript_text: target_lang,
      };
      const transcript = await axios.post(
        `https://api-bhashini-ashwin.plenome.com/upload_transcript`,
        payload,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log(transcript.data, "transcript");

      const transcript_id = transcript.data?.Transcript_Id;

      const speaker_diarized = await axios.get(
        `https://api-bhashini-ashwin.plenome.com/speaker_diarized_transcript?transcript_id=${transcript_id}`,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log("speaker_diarized.data", speaker_diarized.data);

      const soap_notes = await axios.get(
        `https://api-bhashini-ashwin.plenome.com/SOAP_notes?transcript_id=${transcript_id}`,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log(soap_notes.data, "soap_notes");

      const snomed_ct = await axios.get(
        `https://api-bhashini-ashwin.plenome.com/SNOMED_CT?transcript_id=${transcript_id}`,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log(snomed_ct.data, "snomed_ct");

      const icd = await axios.get(
        `https://api-bhashini-ashwin.plenome.com/ICD-10_code?transcript_id=${transcript_id}`,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log(icd.data, "icd");

      const medical_report = await axios.get(
        `https://api-bhashini-ashwin.plenome.com/medical_report?transcript_id=${transcript_id}`,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log(medical_report.data, "medical_report");

      const dental_medical_report = await axios.get(
        `https://api-bhashini-ashwin.plenome.com/dental_medical_report?transcript_id=${transcript_id}`,
        { headers: transcript_header, httpsAgent: httpsAgent }
      );
      console.log(dental_medical_report.data, "dental_medical_report");

      return {
        status: "success",
        message: "Retrieved data successfully",
        data: {
          Transcript_id: transcript_id.data,
          Speaker_diarized: speaker_diarized.data,
          Soap_notes: soap_notes.data,
          Snomed_ct: snomed_ct.data,
          icd: icd.data,
          Medical_report: medical_report.data,
          Dental_medical_report: dental_medical_report.data,
        },
      };
    } catch (error) {
      console.log(error.data, "error");

      return error;
    }
  }
}
