

// import { forwardRef, Inject, Injectable } from '@nestjs/common';
// import * as FormData from 'form-data';
// import axios from 'axios';
// import { PreviewDocService } from 'src/preview_doc/preview_doc.service';
// import { ClinicalNotesWithAbhaService } from 'src/clinical-notes-with-abha/clinical-notes-with-abha.service';
// import { OpdPrescriptionService } from 'src/opd-prescription/opd-prescription.service';
// import { ManualVitalsService } from 'src/manual_vitals/manual_vitals.service';

// @Injectable()
// export class VoiceTextSarvamService {

//   constructor(
//     @Inject(forwardRef(() => PreviewDocService)) private previewService: PreviewDocService,
//     @Inject(forwardRef(() => ClinicalNotesWithAbhaService)) private clinicalNotesService: ClinicalNotesWithAbhaService,
//     @Inject(forwardRef(() => OpdPrescriptionService)) private PrescriptionService: OpdPrescriptionService,
//     @Inject(forwardRef(() => ManualVitalsService)) private vitalsService: ManualVitalsService

//   ) { }


//   async create(files: Express.Multer.File[], opd_id: string, hospital_id: string) {

// let transcriptionText = ''
//     for(const file of files){
//       const form = new FormData();
//       form.append("file", file.buffer, {
//         filename: file.originalname,
//         contentType: file.mimetype,
//       });

//       form.append("model", "saaras:v1");

//       const headers = {
//         'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
//         ...form.getHeaders(),
//       };
//       try {
//         const response = await axios.post('https://api.sarvam.ai/speech-to-text-translate', form, { headers });
//         transcriptionText += response.data.transcript + " "


//       } catch (error) {
//         throw new Error(error);
//       }
//     }


//     try {



//       if (!transcriptionText) {
//         throw new Error('Transcription text is empty or invalid');
//       }

//       const categorizedResponse = await this.categorizeWithAnthropic(transcriptionText, opd_id, hospital_id);
//       let PreviewResponse = await this.previewService.findAll(opd_id, hospital_id)


//       return PreviewResponse;

//     } catch (error) {
//       console.error('Error:', error);
//       throw new Error('Failed to process speech-to-text translation.');
//     }
//   }


//   async categorizeWithAnthropic(transcriptionText: string, opd_id: any, hospital_id: any) {
//     let CurrDate = new Date().toISOString();
//     const currentDate = new Date();

//     const formattedDate = currentDate.toISOString().split("T")[0];
//     const messages = [
//       {
//         role: 'user', content: `This is an example json structure where 
// Appointment Details : opd_id = ${opd_id}, hospital_id is ${hospital_id}, Todaydate is ${formattedDate}
// Transcript : ${transcriptionText} 

// Above is the transcript of the conversation between a doctor and patient. Analyze the conversation and fill the JSON object accordingly, which is the standard format of an EMR. Here are the rules to follow:

// 1. "vitals" is the set of vital parameters mentioned. This might be mentioned in the transcript or the body given in the prompt might already have this. If there's data already in the body, and nothing mentioned in the transcript, do not change those values. If the transcript mentions some value and that value is empty in the body, update the value accordingly. If nothing is mentioned in the transcript and nothing is present in the body, keep it empty.
// 2. The "clinical_notes" consists of all the other details of the consultation under the following keys:
// 	1. "followUp" is the details of the next consultation as suggested by the doctor in the transcript. The "count" is the number of time units and "duration_limit" is the time unit for the number of units after which the follow-up is to be done (this can be days, weeks, fortnights, months or any other unit). "date" should be calculated by adding the number of time units to the date of the consultation. So, if the follow-up is after "5" "days", add 5 days to the date given at the start of the prompt, and that is the value. "remarks" is any comment about the symptom or disease mentioned by he doctor or the patient in the conversation, which is to be written as text here.
// 	2. "dietPlan" is an dietary restrictions or advice given in the conversation to the patient, like "have warm water every morning", "reduce oily food", "do not consume milk" or something of this sort, which is to be added under the key "diet_plan". If any dietary advice is not mentioned in the transcript, keep this empty. 
// 	3. "diagnosisReport" is an array which consists of the diagnostic tests the patient is prescribed to undergo by the doctor. For every test mentioned, these are the details of each key under this object: "sub_category" is the name of the actual test to be talen (for example, complete blood count (CBC test), thyroid level test, blood glucose test), based on which the "test_categories" has to be identified. For example, a CBC test or urine test comes under pathology, and hence the "test_categories" will be "pathology". Find the category accordingly and update. "laboratory" is the name of the laboratory mentioned by the doctor to the patient, where the test has to be taken. If no laboratory name is mentioned, leave this empty. "remarks" is any additional comment mentioned by the doctor about the test, and leave this empty if nothing additional is commented by the doctor. If no diagnostic test is prescribed in the transcript, keep this empty.
// 	4. "treatmentAdvice" is the diagnosis of the symptom/disease of the patient and any advice to the patient as mentioned by the doctor in the transcript. This should be updated under the "advice" key, and should consist of text of the advice given by the doctor.
// 	5. "pastTreatmentHistory" is the past medical history of the patient which is mentioned in the transcript either by the doctor or the patient. Extract this from the transcript and fill the text to the "history" key. 
// 	6. "pastTreatmentHistoryDocs" is the list of documents shared by the patient for reference of their medical history. Leave this as it is, do not change this. 
// 	7. The symptoms and complaints of the disease mentioned by the patient in the transcript are filled under the two arrays - "chiefComplaintDetails" consists of the detailed descriptions of each of the complaints mentioned in the transcript with all details, and "chiefComplaintsBasic" are the same complaints mentioned objectively without the details. For example, ["severe head ache from the past 3 days", "occasional stomach pain"] mentioned under "chiefComplaintDetails" will be stored as ["headache", "stomach pain"] under "chiefComplaintsBasic". If no complaint/symptom is mentioned, keep this empty. 
// 3. The key "prescription" consists of the medications prescribed by the doctor in an array. The objects in this array should have medicines with the following: 
// 	1. "medicine_name" is the name of the medication prescribed. If no medicine name is mentioned in the transcript, then the "prescription" array remains empty completely. 
// 	2. "frequency" should day how many times the medicine is to be taken and at what time in a single day. For example 1-0-1 of a tablet means 1 unit in the morning, 0 in the afternoon, and 1 in the evening. Understand this from the transcript of the conversation and convert it accordingly. If no frequency is mentioned, keep this empty.
// 	3. "dosage" consists of the dosage of the medication given, and is mention by the doctor in the transcript usually in milligrams or with the medicine name. If no number for the dosage is mentioned, keep this empty.
// 	4. "duration_count" and "duration_limit" are is the number of time period units the medicine has to be taken for a given time period. This will either be said in the conversation, or can be calculated from other clues - if the doctor says 6 tablets with 1-0-1, it means it's for 3 days, since each day there's 2 tablets to be consumed, hence the "duration_count" is 3, and the "duration_limit" is "days". If no duration count or limit is mentioned, keep these fields empty.
// 	6. "quantity" is the total number of units of the medication to be consumed over the total period. For example, if the frequency is "1-0-1", and the "duration_count" is 5, and the "duration_limit" is "days", this means that each day there 1+0+1 tablets (2 tablets) to be taken every day for 5 days, which counts to 2*5, that is 10 tablets to be consumed. So, this field is calculated from the "frequency" and "duration_count" values. 
// 	7. "when" is the time when the medication has to be taken. This might be "before meal all times", "after meal at night, before meal in morning", "on empty stomach in morning" and other variations of the timing the medicine has to be taken by the patient (not limited to these mentioned here). One medicine which is to be taken more than once in a day, can have multiple "when" conditions for the different consumption times, so all these conditions have to be mentioned. If no proper timings are mentioned, keep these fields empty.
// 	8. "remarks" is some other comment on the instructions for the medication consumption, maybe "take it with water", or "with warm water", or something else even about the condition of the patient, like "consume this only if there's a headache" or some other comment. If no additional remark about the medication is mentioned, keep this empty.

// 7. If the relevant data for a particular field doesm't exist in the trasncript after your analysis, don't enter anything, and if the key has an object array, keep the array empty. For example, if there are no medicine names mentioned in the transcript clearly, keep the "prescriptions" array empty. On the other hand if the "followUp" doesn't have any relevant data from the transcript, just keep the value to the keys empty inside the "followUp" object.

// 8. Fields mentioned as "<to be filled from Transcript>" should be extracted from text under the "Transcript" heading in the prompt and processed as per the guidelines mentioned above and then updated, and "<to be filled from Appointment Details>" should be filled from the text under the "Appointment Details" heading.

// {
// "vitals":{
//   "spo2": "<to be filled from Transcript>",
//   "respiration": "<to be filled from Transcript>",
//   "temperature": "<to be filled from Transcript>",
//   "pulse": "<to be filled from Transcript>",
//   "weight": "<to be filled from Transcript>",
//   "height": "<to be filled from Transcript>",
//   "bp": "<to be filled from Transcript>"
// },

// "clinical_notes": {
//     "followUp": {
//       "opd_id": "<to be filled from Appointment Details>",
//       "count": "<to be filled from Transcript>",
//       "duration_limit": "<to be filled from Transcript>",
//       "date": "<to be filled from Transcript>",
//       "remarks": "<to be filled from Transcript>",
//       "filled_using": "voice"
//     },
//     "dietPlan": {
//       "opd_id": "<to be filled from Appointment Details>",
//       "diet_plan": "<to be filled from Transcript>",
//       "filled_using": "voice"
//     },
//     "diagnosisReport": [
//       {
//         "opd_id": "<to be filled from Appointment Details>",
//         "test_categories": "<to be filled from Transcript>",
//         "sub_category": "<to be filled from Transcript>",
//         "laboratory": "<to be filled from Transcript>",
//         "remarks": "<to be filled from Transcript>",
//         "filled_using": "voice"
//       }
//     ],
//     "treatmentAdvice": {
//       "opd_id": "<to be filled from Appointment Details>",
//       "advice": "<to be filled from Transcript>",
//       "filled_using": "voice"
//     },
//     "pastTreatmentHistory": {
//       "opd_id": "<to be filled from Appointment Details>",
//       "history": "<to be filled from Transcript>",
//       "filled_using": "voice"
//     },
//     "chiefComplaintsBasic": [
//       {
//         "opd_id": "<to be filled from Appointment Details>",
//         "complaint_name": "<to be filled from Transcript >",
//         "filled_using": "voice"
//       }
//     ],
//     "chiefComplaintDetails": {
//       "opd_id": "<to be filled from Appointment Details>",,
//       "count": "<to be filled from Transcript>",
//       "duration_limit": "<to be filled from Transcript>",
//       "remarks": "<to be filled from Transcript>",
//       "filled_using": "voice"
//     },
//     "hospital_id": "<to be filled from Appointment Details>"
//   },

//   "prescription": [
//     {
//       "medicine_name": "<to be filled from Transcript>",
//       "frequency": "<to be filled from Transcript>",
//       "dosage": "<to be filled from Transcript>",
//       "duration_count": "<to be filled from Transcript>",
//       "duration_limit": "<to be filled from Transcript>",
//       "quantity": "<to be filled from Transcript>",
//       "when": "<to be filled from Transcript>",
//       "remarks": "<to be filled from Transcript>",
//       "filled_using": "voice",
//       "opd_id": <to be filled from Appointment Details>,
//       "hospital_id": <to be filled from Appointment Details>
//     },
//   ],

//   "Bundle": []
// }

// After the above JSON body is created, take the entries in the "chiefComplaintDetails", and break down the "complaint_name" key's values into individual symptoms. For every symptom, create a JSON object as per the format given below with its matching SNOMED code of the latest version, while updating only the entries under the "code" key which has the "coding" key under it, which has the SNOMED code to be mentioned in the "code" key, and the actual symptom to be declared in "display" key. If there are multiple symptoms, make multiple objects, while updating the "[i]" with the array indices 0,1,2,... while keeping the square brackets. Other than the iterative variable i, only update the values mentioned as "<to be filled>":, push all the created json into "Bundle" provided above

// {  
//     "fullUrl": "urn:uuid:ChifeCompIDs[i]",  
//     "resource": {  
//         "resourceType": "Condition",  
//         "id": "ChifeCompIDs[i]",  
//         "meta": {  
//             "profile": [  
//                 "[[https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition"](https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition%22](https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition%22](https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition%22 "https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22](https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22") "[https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22")](https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22%22) "https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22%22)")  
//             ]  
//         },  
//         "clinicalStatus": {  
//             "coding": [  
//                 {  
//                     "system": "[[http://terminology.hl7.org/CodeSystem/condition-clinical"](http://terminology.hl7.org/CodeSystem/condition-clinical%22](http://terminology.hl7.org/CodeSystem/condition-clinical%22](http://terminology.hl7.org/CodeSystem/condition-clinical%22 "http://terminology.hl7.org/codesystem/condition-clinical%22](http://terminology.hl7.org/codesystem/condition-clinical%22") "[http://terminology.hl7.org/codesystem/condition-clinical%22")](http://terminology.hl7.org/codesystem/condition-clinical%22%22) "http://terminology.hl7.org/codesystem/condition-clinical%22%22)"),  
//                     "code": "active",  
//                     "display": "Active"  
//                 }  
//             ]  
//         },  
//         "code": {  
//             "coding": [  
//                 {  
//                     "system": "[[http://snomed.info/sct"](http://snomed.info/sct%22](http://snomed.info/sct%22](http://snomed.info/sct%22 "http://snomed.info/sct%22](http://snomed.info/sct%22") "[http://snomed.info/sct%22")](http://snomed.info/sct%22%22) "http://snomed.info/sct%22%22)"),  
//                     "code": "<to be filled>",  
//                     "display": "<to be filled>"  
//                 }  
//             ],  
//             "text": "symps?.complaints_name"  
//         },  
//         "subject": {  
//             "reference": "urn:uuid:PatientID",  
//             "display": "Patient"  
//         }  
//     }  
// }

// Only give the JSON objects, no other explanation needed.`,
//       }
//     ];

//     const headers = {
//       'x-api-key': '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',
//       'anthropic-version': '2023-06-01',
//       'Content-Type': 'application/json',
//     };

//     const anthropicData = {
//       model: 'claude-3-5-sonnet-20241022',
//       max_tokens: 8192,
//       messages: messages,
//     };



//     try {
//       const response = await axios.post('https://api.anthropic.com/v1/messages', anthropicData, { headers });


//       let summa = await response.data.content[0].text

//       let dongri = await JSON.parse(summa)




//       const uniqueclinical_notes_chiefcomplaints = dongri.clinical_notes.chiefComplaintsBasic.filter((item, index, self) =>
//         index === self.findIndex((t) =>
//             t.complaint_name.toLocaleLowerCase() === item.complaint_name.toLocaleLowerCase()
//         )
//     );
//     dongri.clinical_notes.chiefComplaintsBasic = uniqueclinical_notes_chiefcomplaints
//       const post_clinical_notes = await this.clinicalNotesService.create(dongri.clinical_notes)

//       const postVitals = await this.vitalsService.create(dongri.vitals,opd_id,hospital_id)
//       const uniquePrescriptions = dongri.prescription.filter((item, index, self) =>
//         index === self.findIndex((t) =>
//             t.medicine_name.toLowerCase() === item.medicine_name.toLowerCase()
//         )
//     );

//       for (const a of uniquePrescriptions) {
//         const post_prescription = await this.PrescriptionService.create(a)


//       }
//       return response.data;
//     } catch (error) {
//       console.error('Error categorizing with Anthropic:', error);

//       if (error.response) {
//         console.error('Anthropic API Error Response:', error.response.data);
//       } else if (error.request) {
//         console.error('Anthropic API No Response:', error.request);
//       } else {
//         console.error('General Error:', error.message);
//       }

//       throw new Error('Failed to categorize the transcription text.');
//     }
//   }
// }



import { forwardRef, Inject, Injectable } from '@nestjs/common';
import * as FormData from 'form-data';
import axios from 'axios';
import { PreviewDocService } from 'src/preview_doc/preview_doc.service';
import { ClinicalNotesWithAbhaService } from 'src/clinical-notes-with-abha/clinical-notes-with-abha.service';
import { OpdPrescriptionService } from 'src/opd-prescription/opd-prescription.service';
import { ManualVitalsService } from 'src/manual_vitals/manual_vitals.service';
import { HttpException } from '@nestjs/common';
import { HttpStatus } from '@nestjs/common';
import { DataLakeFileClient, DataLakeServiceClient } from '@azure/storage-file-datalake';
import { promisify } from 'util';
import { BadRequestException } from '@nestjs/common';
import * as fs from 'fs';
import * as mime from 'mime-types';
import * as path from 'path';
import { Readable } from 'form-data';
import SarvamClient from './lib/sarvam-client-old';
import { SttTranslateSarvamService } from 'src/stt-translate-sarvam/stt-translate-sarvam.service';



@Injectable()
export class VoiceTextSarvamService {

  constructor(
    @Inject(forwardRef(() => PreviewDocService)) private previewService: PreviewDocService,
    @Inject(forwardRef(() => ClinicalNotesWithAbhaService)) private clinicalNotesService: ClinicalNotesWithAbhaService,
    @Inject(forwardRef(() => OpdPrescriptionService)) private PrescriptionService: OpdPrescriptionService,
    @Inject(forwardRef(() => ManualVitalsService)) private vitalsService: ManualVitalsService,
    @Inject(forwardRef(() => SttTranslateSarvamService)) private SttService: SttTranslateSarvamService

  ) {
    // let storage_path = this.initialize()
    // let uploadUrl = storage_path.input_storage_path
    // const { accountUrl, fileSystemName, directoryName, sasToken } = this.extractUrlComponents(uploadUrl);

    // const serviceClient = new DataLakeServiceClient(`${accountUrl}${sasToken}`);
    // const fileSystemClient = serviceClient.getFileSystemClient(fileSystemName);
    // const directoryClient = fileSystemClient.getDirectoryClient(directoryName);

  }



  async create(opd_id: string, hospital_id: string) {



    let transcriptionText = await this.SttService.downloadFileAsZip(opd_id, hospital_id)

    console.log(transcriptionText, "transcriptionText");


    try {



      if (!transcriptionText) {
        throw new Error('Transcription text is empty or invalid');
      }

      const categorizedResponse = await this.categorizeWithAnthropic(transcriptionText, opd_id, hospital_id);
      let PreviewResponse = await this.previewService.findAll(opd_id, hospital_id)


      return PreviewResponse;

    } catch (error) {
      console.error('Error:', error);
      throw new Error('Failed to process speech-to-text translation.');
    }
  }


  async categorizeWithAnthropic(transcriptionText: string, opd_id: any, hospital_id: any) {
    let CurrDate = new Date().toISOString();
    const currentDate = new Date();

    const formattedDate = currentDate.toISOString().split("T")[0];
    const messages = [
      {
        role: 'user', content: `This is an example json structure where 
Appointment Details : opd_id = ${opd_id}, hospital_id is ${hospital_id}, Todaydate is ${formattedDate}
Transcript : ${transcriptionText} 

Above is the transcript of the conversation between a doctor and patient. Analyze the conversation and fill the JSON object accordingly, which is the standard format of an EMR. Here are the rules to follow:

1. "vitals" is the set of vital parameters mentioned. This might be mentioned in the transcript or the body given in the prompt might already have this. If there's data already in the body, and nothing mentioned in the transcript, do not change those values. If the transcript mentions some value and that value is empty in the body, update the value accordingly. If nothing is mentioned in the transcript and nothing is present in the body, keep it empty.
2. The "clinical_notes" consists of all the other details of the consultation under the following keys:
	1. "followUp" is the details of the next consultation as suggested by the doctor in the transcript. The "count" is the number of time units and "duration_limit" is the time unit for the number of units after which the follow-up is to be done (this can be days, weeks, fortnights, months or any other unit). "date" should be calculated by adding the number of time units to the date of the consultation. So, if the follow-up is after "5" "days", add 5 days to the date given at the start of the prompt, and that is the value. "remarks" is any comment about the symptom or disease mentioned by he doctor or the patient in the conversation, which is to be written as text here.
	2. "dietPlan" is an dietary restrictions or advice given in the conversation to the patient, like "have warm water every morning", "reduce oily food", "do not consume milk" or something of this sort, which is to be added under the key "diet_plan". If any dietary advice is not mentioned in the transcript, keep this empty. 
	3. "diagnosisReport" is an array which consists of the diagnostic tests the patient is prescribed to undergo by the doctor. For every test mentioned, these are the details of each key under this object: "sub_category" is the name of the actual test to be talen (for example, complete blood count (CBC test), thyroid level test, blood glucose test), based on which the "test_categories" has to be identified. For example, a CBC test or urine test comes under pathology, and hence the "test_categories" will be "pathology". Find the category accordingly and update. "laboratory" is the name of the laboratory mentioned by the doctor to the patient, where the test has to be taken. If no laboratory name is mentioned, leave this empty. "remarks" is any additional comment mentioned by the doctor about the test, and leave this empty if nothing additional is commented by the doctor. If no diagnostic test is prescribed in the transcript, keep this empty.
	4. "treatmentAdvice" is the diagnosis of the symptom/disease of the patient and any advice to the patient as mentioned by the doctor in the transcript. This should be updated under the "advice" key, and should consist of text of the advice given by the doctor.
	5. "pastTreatmentHistory" is the past medical history of the patient which is mentioned in the transcript either by the doctor or the patient. Extract this from the transcript and fill the text to the "history" key. 
	6. "pastTreatmentHistoryDocs" is the list of documents shared by the patient for reference of their medical history. Leave this as it is, do not change this. 
	7. The symptoms and complaints of the disease mentioned by the patient in the transcript are filled under the two arrays - "chiefComplaintDetails" consists of the detailed descriptions of each of the complaints mentioned in the transcript with all details, and "chiefComplaintsBasic" are the same complaints mentioned in single object without the details. For example, ["severe head ache from the past 3 days", "occasional stomach pain"] mentioned under "chiefComplaintDetails" will be stored as ["headache", "stomach pain", "nausea"] separated by commas in complaints_name field not as separate entries under "chiefComplaintsBasic". If no complaint/symptom is mentioned, keep this empty. 
3. The key "prescription" consists of the medications prescribed by the doctor in an array. The objects in this array should have medicines with the following: 
	1. "medicine_name" is the name of the medication prescribed. If no medicine name is mentioned in the transcript, then the "prescription" array remains empty completely. 
	2. "frequency" should day how many times the medicine is to be taken and at what time in a single day. For example 1-0-1 of a tablet means 1 unit in the morning, 0 in the afternoon, and 1 in the evening. Understand this from the transcript of the conversation and convert it accordingly. If no frequency is mentioned, keep this empty.
	3. "dosage" consists of the dosage of the medication given, and is mention by the doctor in the transcript usually in milligrams or with the medicine name. If no number for the dosage is mentioned, keep this empty.
	4. "duration_count" and "duration_limit" are is the number of time period units the medicine has to be taken for a given time period. This will either be said in the conversation, or can be calculated from other clues - if the doctor says 6 tablets with 1-0-1, it means it's for 3 days, since each day there's 2 tablets to be consumed, hence the "duration_count" is 3, and the "duration_limit" is "days". If no duration count or limit is mentioned, keep these fields empty.
	6. "quantity" is the total number of units of the medication to be consumed over the total period. For example, if the frequency is "1-0-1", and the "duration_count" is 5, and the "duration_limit" is "days", this means that each day there 1+0+1 tablets (2 tablets) to be taken every day for 5 days, which counts to 2*5, that is 10 tablets to be consumed. So, this field is calculated from the "frequency" and "duration_count" values. 
	7. "when" is the time when the medication has to be taken. This might be "before meal all times", "after meal at night, before meal in morning", "on empty stomach in morning" and other variations of the timing the medicine has to be taken by the patient (not limited to these mentioned here). One medicine which is to be taken more than once in a day, can have multiple "when" conditions for the different consumption times, so all these conditions have to be mentioned. If no proper timings are mentioned, keep these fields empty.
	8. "remarks" is some other comment on the instructions for the medication consumption, maybe "take it with water", or "with warm water", or something else even about the condition of the patient, like "consume this only if there's a headache" or some other comment. If no additional remark about the medication is mentioned, keep this empty.

7. If the relevant data for a particular field doesm't exist in the trasncript after your analysis, don't enter anything, and if the key has an object array, keep the array empty. For example, if there are no medicine names mentioned in the transcript clearly, keep the "prescriptions" array empty. On the other hand if the "followUp" doesn't have any relevant data from the transcript, just keep the value to the keys empty inside the "followUp" object.

8. Fields mentioned as "<to be filled from Transcript>" should be extracted from text under the "Transcript" heading in the prompt and processed as per the guidelines mentioned above and then updated, and "<to be filled from Appointment Details>" should be filled from the text under the "Appointment Details" heading.

{
"vitals":{
  "spo2": "<to be filled from Transcript>",
  "respiration": "<to be filled from Transcript>",
  "temperature": "<to be filled from Transcript>",
  "pulse": "<to be filled from Transcript>",
  "weight": "<to be filled from Transcript>",
  "height": "<to be filled from Transcript>",
  "bp": "<to be filled from Transcript>"
},

"clinical_notes": {
    "followUp": {
      "opd_id": "<to be filled from Appointment Details>",
      "count": "<to be filled from Transcript>",
      "duration_limit": "<to be filled from Transcript>",
      "date": "<to be filled from Transcript>",
      "remarks": "<to be filled from Transcript>",
      "filled_using": "voice"
    },
    "dietPlan": {
      "opd_id": "<to be filled from Appointment Details>",
      "diet_plan": "<to be filled from Transcript>",
      "filled_using": "voice"
    },
    "diagnosisReport": [
      {
        "opd_id": "<to be filled from Appointment Details>",
        "test_categories": "<to be filled from Transcript>",
        "sub_category": "<to be filled from Transcript>",
        "laboratory": "<to be filled from Transcript>",
        "remarks": "<to be filled from Transcript>",
        "filled_using": "voice"
      }
    ],
    "treatmentAdvice": {
      "opd_id": "<to be filled from Appointment Details>",
      "advice": "<to be filled from Transcript>",
      "filled_using": "voice"
    },
    "pastTreatmentHistory": {
      "opd_id": "<to be filled from Appointment Details>",
      "history": "<to be filled from Transcript>",
      "filled_using": "voice"
    },
    "chiefComplaintsBasic": [
      {
        "opd_id": "<to be filled from Appointment Details>",
        "complaint_name": "<to be filled from Transcript >",
        "filled_using": "voice"
      }
    ],
    "chiefComplaintDetails": {
      "opd_id": "<to be filled from Appointment Details>",,
      "count": "<to be filled from Transcript>",
      "duration_limit": "<to be filled from Transcript>",
      "remarks": "<to be filled from Transcript>",
      "filled_using": "voice"
    },
    "hospital_id": "<to be filled from Appointment Details>"
  },

  "prescription": [
    {
      "medicine_name": "<to be filled from Transcript>",
      "frequency": "<to be filled from Transcript>",
      "dosage": "<to be filled from Transcript>",
      "duration_count": "<to be filled from Transcript>",
      "duration_limit": "<to be filled from Transcript>",
      "quantity": "<to be filled from Transcript>",
      "when": "<to be filled from Transcript>",
      "remarks": "<to be filled from Transcript>",
      "filled_using": "voice",
      "opd_id": <to be filled from Appointment Details>,
      "hospital_id": <to be filled from Appointment Details>
    },
  ],

  "Bundle": []
}

After the above JSON body is created, take the entries in the "chiefComplaintDetails", and break down the "complaint_name" key's values into individual symptoms. For every symptom, create a JSON object as per the format given below with its matching SNOMED code of the latest version, while updating only the entries under the "code" key which has the "coding" key under it, which has the SNOMED code to be mentioned in the "code" key, and the actual symptom to be declared in "display" key. If there are multiple symptoms, make multiple objects, while updating the "[i]" with the array indices 0,1,2,... while keeping the square brackets. Other than the iterative variable i, only update the values mentioned as "<to be filled>":, push all the created json into "Bundle" provided above

{  
    "fullUrl": "urn:uuid:ChifeCompIDs[i]",  
    "resource": {  
        "resourceType": "Condition",  
        "id": "ChifeCompIDs[i]",  
        "meta": {  
            "profile": [  
                "[[https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition"](https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition%22](https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition%22](https://nrces.in/ndhm/fhir/r4/StructureDefinition/Condition%22 "https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22](https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22") "[https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22")](https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22%22) "https://nrces.in/ndhm/fhir/r4/structuredefinition/condition%22%22)")  
            ]  
        },  
        "clinicalStatus": {  
            "coding": [  
                {  
                    "system": "[[http://terminology.hl7.org/CodeSystem/condition-clinical"](http://terminology.hl7.org/CodeSystem/condition-clinical%22](http://terminology.hl7.org/CodeSystem/condition-clinical%22](http://terminology.hl7.org/CodeSystem/condition-clinical%22 "http://terminology.hl7.org/codesystem/condition-clinical%22](http://terminology.hl7.org/codesystem/condition-clinical%22") "[http://terminology.hl7.org/codesystem/condition-clinical%22")](http://terminology.hl7.org/codesystem/condition-clinical%22%22) "http://terminology.hl7.org/codesystem/condition-clinical%22%22)"),  
                    "code": "active",  
                    "display": "Active"  
                }  
            ]  
        },  
        "code": {  
            "coding": [  
                {  
                    "system": "[[http://snomed.info/sct"](http://snomed.info/sct%22](http://snomed.info/sct%22](http://snomed.info/sct%22 "http://snomed.info/sct%22](http://snomed.info/sct%22") "[http://snomed.info/sct%22")](http://snomed.info/sct%22%22) "http://snomed.info/sct%22%22)"),  
                    "code": "<to be filled>",  
                    "display": "<to be filled>"  
                }  
            ],  
            "text": "symps?.complaints_name"  
        },  
        "subject": {  
            "reference": "urn:uuid:PatientID",  
            "display": "Patient"  
        }  
    }  
}

Only give the JSON objects, no other explanation needed.`,
      }
    ];

    const headers = {
      'x-api-key': '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',
      'anthropic-version': '2023-06-01',
      'Content-Type': 'application/json',
    };

    const anthropicData = {
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 8192,
      messages: messages,
    };



    try {
      const response = await axios.post('https://api.anthropic.com/v1/messages', anthropicData, { headers });


      let summa = await response.data.content[0].text

      let dongri = await JSON.parse(summa)




      const uniqueclinical_notes_chiefcomplaints = dongri.clinical_notes.chiefComplaintsBasic.filter((item, index, self) =>
        index === self.findIndex((t) =>
          t.complaint_name.toLocaleLowerCase() === item.complaint_name.toLocaleLowerCase()
        )
      );
      dongri.clinical_notes.chiefComplaintsBasic = uniqueclinical_notes_chiefcomplaints
      const post_clinical_notes = await this.clinicalNotesService.create(dongri.clinical_notes)

      const postVitals = await this.vitalsService.create(dongri.vitals, opd_id, hospital_id)
      const uniquePrescriptions = dongri.prescription.filter((item, index, self) =>
        index === self.findIndex((t) =>
          t.medicine_name.toLowerCase() === item.medicine_name.toLowerCase()
        )
      );

      for (const a of uniquePrescriptions) {
        const post_prescription = await this.PrescriptionService.create(a)


      }
      console.log(response.data, "response.data");

      return response.data;
    } catch (error) {
      console.error('Error categorizing with Anthropic:', error);

      if (error.response) {
        console.error('Anthropic API Error Response:', error.response.data);
      } else if (error.request) {
        console.error('Anthropic API No Response:', error.request);
      } else {
        console.error('General Error:', error.message);
      }

      throw new Error('Failed to categorize the transcription text.');
    }
  }


  // private extractUrlComponents(url: string) {
  //   const parsedUrl = new URL(url);
  //   console.log(parsedUrl, "parsedUrl");

  //   let accountUrl = parsedUrl.origin.replace(".blob.", ".dfs.");
  //   const pathComponents = parsedUrl.pathname.split("/").filter(Boolean);
  //   // const fileSystemName = pathComponents[0];
  //   const fileSystemName = pathComponents[0] || '';
  //   // if (fileSystemName) {
  //   //     accountUrl = `${accountUrl}/${fileSystemName}`;
  //   // }
  //   const directoryName = pathComponents.slice(1).join("/");
  //   const sasToken = parsedUrl.search;
  //   console.log(sasToken, "sasToken");


  //   return { accountUrl, fileSystemName, directoryName, sasToken };
  // }


  //   private async initStorage(uploadUrl, fileName, filedata, mimetype) {
  //     try {


  //       const { accountUrl, fileSystemName, directoryName, sasToken } = this.extractUrlComponents(uploadUrl);

  //       console.log(accountUrl,"accountUrl", fileSystemName, directoryName, "sasToken", sasToken, "march1333");
  //       console.log("Received uploadUrl:", uploadUrl);


  //       const serviceClient = new DataLakeServiceClient(`${accountUrl}${sasToken}`);
  //       const fileSystemClient = serviceClient.getFileSystemClient(fileSystemName);
  //       const directoryClient = fileSystemClient.getDirectoryClient(directoryName);

  //       // const fileSystem_Client = serviceClient.getFileSystemClient(fileSystemName);
  //       // const directory_Client = fileSystem_Client.getDirectoryClient(directoryName);
  //       // const fileClient = directory_Client.getFileClient(fileName);
  //       const fileClient = directoryClient.getFileClient(fileName);
  //       console.log(fileClient, "fileClienttt");




  //       try {
  //       //   console.log(filedata, "filedata");

  //       //   const upload_final = await fileClient.uploadData(filedata, { overwrite: true, contentType: mimetype });
  //       // console.log(upload_final, "upload_final");
  //       // console.log(`Creating file: ${fileName}`);

  //             await fileClient.create();
  //             console.log(`Appending data: ${filedata.length} bytes`);
  //             await fileClient.append(filedata, 0, filedata.length);
  //             console.log(`Flushing data...`);
  //             await fileClient.flush(filedata.length);
  //             console.log(`Setting content type: ${mimetype}`);

  //   // // Step 4: Set content type separately
  //   await fileClient.setHttpHeaders({ contentType: mimetype });
  //   return { success: true, message: 'File uploaded successfully' };
  //   // const properties = await fileClient.getProperties();
  //   // console.log("File properties:", properties);
  // //   const blobServiceClient = new BlobServiceClient(`${accountUrl}${sasToken}`);
  // // const containerClient = blobServiceClient.getContainerClient(fileSystemName);
  // // const blobClient = containerClient.getBlockBlobClient(fileName);

  // // await blobClient.uploadData(filedata, { blobHTTPHeaders: { blobContentType: mimetype } });
  //       } catch (error) {
  //         console.log(error, "upload_error");

  //       }


  //       // console.log(` File uploaded successfully: ${fileName}`);
  //       // return true;

  //       console.log("Storage initialized successfully!");
  //     } catch (error) {
  //       console.error("Storage initialization failed:", error.message);
  //     }
  //   }



  //   async initialize(files:any):Promise<{
  //     input_storage_path:string
  //   }>{
  //     const headers = {
  //       'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64'
  //     };
  //     console.log(files, "filesss");


  //     try {
  //       const init_response = await axios.post('https://api.sarvam.ai/speech-to-text-translate/job/init', '', { headers });


  //       if (!init_response.data.input_storage_path) {
  //         throw new HttpException('No input storage path provided', HttpStatus.BAD_REQUEST);
  //       }
  //       // const { accountUrl, fileSystemName, directoryName, sasToken } = this.extractUrlComponents(init_response.data.input_storage_path);
  //       const parsedUrl = new URL(init_response.data.input_storage_path);
  //       const dfsurl = parsedUrl.origin.replace(".blob.", ".dfs.") + parsedUrl.pathname + parsedUrl.search;

  //       console.log(parsedUrl, "parsedUrl");

  //       // let accountUrl = parsedUrl.origin.replace(".blob.", ".dfs.");
  //       const pathComponents = parsedUrl.pathname;
  //       // const fileSystemName = pathComponents[0];
  //       const pathParts = parsedUrl.pathname.split("/").filter(Boolean);
  //       const fileSystemName = pathParts[0];
  //       // if (fileSystemName) {
  //       //     accountUrl = `${accountUrl}/${fileSystemName}`;
  //       // }
  //       const directoryName = pathParts.slice(1).join("/"); 
  //       const sasToken = parsedUrl.search;
  //       console.log(sasToken, "sasToken");
  //       for(const file of files){

  //         // await this.initStorage(init_response.data.input_storage_path, file.originalname, file.buffer, file.mimetype)
  //         this.uploadFile(file, fileSystemName, directoryName, init_response.data.input_storage_path, dfsurl)
  //       }

  //       return init_response.data;






  //       // const uploadResults = [];

  //       // for (const file of files) {
  //       //   const fileClient = directoryClient.getFileClient(file.originalname);
  //       //   const mimeType = mime.lookup(file.originalname) || 'application/octet-stream';

  //       //   await fileClient.uploadData(file.buffer, { overwrite: true, contentType: mimeType });

  //       //   uploadResults.push({
  //       //     fileName: file.originalname,
  //       //     status: 'uploaded',
  //       //   });
  //       // }

  //       // return {
  //       //   status: 'success',
  //       //   message: 'Files uploaded successfully'
  //       // };

  //     } catch (error) {
  //       throw new Error(error);
  //     }
  //   }

  //   async uploadFile(file: Express.Multer.File, fileSystemName, directoryName, sasUrl, dfsurl ): Promise<string> {
  //     if (!file) {
  //       throw new BadRequestException('File is required');
  //     }

  //     const fileName = file.originalname;
  //     console.log(`Uploading file: ${fileName}`);


  //     try {
  //       // Get reference to the directory
  //       const accountUrl = new URL(dfsurl).origin;
  //       const dataLakeServiceClient = new DataLakeServiceClient(`${accountUrl}${sasUrl}`);
  //       const fileSystemClient = dataLakeServiceClient.getFileSystemClient(fileSystemName);
  //       const directoryClient = fileSystemClient.getDirectoryClient(directoryName);
  //       // const fileClient: DataLakeFileClient = directoryClient.getFileClient(fileName);


  //       const fileClient: DataLakeFileClient = directoryClient.getFileClient(fileName);

  //       // Upload the file
  //       await fileClient.append(file.buffer, 0, file.buffer.length);
  //       await fileClient.flush(file.buffer.length);

  //       console.log(` File uploaded successfully: ${fileName}`);
  //       return `File uploaded: ${fileName}`;
  //     } catch (error) {
  //       console.error(` Upload failed for ${fileName}:`, error.message);
  //       throw new BadRequestException('Upload failed');
  //     }


  // }

  // async initialize(files: Express.Multer.File[]): Promise<{ input_storage_path: string }> {
  //   const headers = {
  //     'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64'
  //   };

  //   console.log(files, "🔍 Files Received:");

  //   try {
  //     const init_response = await axios.post(
  //       'https://api.sarvam.ai/speech-to-text-translate/job/init',
  //       '',
  //       { headers }
  //     );

  //     if (!init_response.data.input_storage_path) {
  //       throw new HttpException('No input storage path provided', HttpStatus.BAD_REQUEST);
  //     }


  //     const parsedUrl = new URL(init_response.data.input_storage_path);
  //     console.log(parsedUrl, "🔍 Parsed URL:");

  //     // Extract file system (container) and directory path
  //     const pathParts = parsedUrl.pathname.split("/").filter(Boolean);
  //     if (pathParts.length < 2) {
  //       throw new HttpException('Invalid input storage path format', HttpStatus.BAD_REQUEST);
  //     }

  //     const fileSystemName = pathParts[0]; // Container name
  //     const directoryName = pathParts.slice(1).join("/"); // Directory name

  //     const dfsUrl = parsedUrl.origin.replace(".blob.", ".dfs.") + parsedUrl.pathname + parsedUrl.search;
  //     console.log(`🔍 DFS URL: ${dfsUrl}`);
  //     console.log(`🔍 FileSystem: ${fileSystemName}, Directory: ${directoryName}`);

  //     for (const file of files) {
  //       console.log(`🚀 Uploading: ${file.originalname} (${file.size} bytes)`);
  //       await this.uploadFile(file, fileSystemName, directoryName, dfsUrl);
  //     }

  //     console.log("✅ All files uploaded successfully!");
  //     return init_response.data;
  //   } catch (error) {
  //     console.error("❌ Error in initialize:", error.message);
  //     throw new Error(error);
  //   }
  // }

  private accountUrl: string;
  private fileSystemName: string;
  private directoryName: string;
  private sasToken: string;



  // Update URL components dynamically
  updateUrl(url: string) {
    const { accountUrl, fileSystemName, directoryName, sasToken } = this.extractUrlComponents(url);
    this.accountUrl = accountUrl;
    this.fileSystemName = fileSystemName;
    this.directoryName = directoryName;
    this.sasToken = sasToken;
  }

  // Extract URL components
  private extractUrlComponents(url: string) {
    const parsedUrl = new URL(url);
    const accountUrl = parsedUrl.origin.replace('.blob.', '.dfs.');
    const pathComponents = parsedUrl.pathname.split('/').filter(Boolean);
    const fileSystemName = pathComponents.shift();
    const directoryName = pathComponents.join('/');
    const sasToken = parsedUrl.searchParams.toString();

    return { accountUrl, fileSystemName, directoryName, sasToken };
  }

  // Upload file as form-data
  // async uploadFile(file: Express.Multer.File) {
  //   console.log(file[0].buffer,"file");

  //   const headers = {
  //           'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64'
  //         };
  //   const init_response = await axios.post(
  //           'https://api.sarvam.ai/speech-to-text-translate/job/init',
  //           '',
  //           { headers }
  //         );

  //         if (!init_response.data.input_storage_path) {
  //           throw new HttpException('No input storage path provided', HttpStatus.BAD_REQUEST);
  //         }

  //   this.updateUrl(init_response.data.input_storage_path)
  //   if (!this.accountUrl || !this.fileSystemName || !this.directoryName) {
  //     throw new Error('Azure Data Lake URL is not set');
  //   }

  //   try {
  //     const serviceClient = new DataLakeServiceClient(`${this.accountUrl}?${this.sasToken}`);
  //     const fileSystemClient = serviceClient.getFileSystemClient(this.fileSystemName);
  //     const directoryClient = fileSystemClient.getDirectoryClient(this.directoryName);
  //     const fileClient = directoryClient.getFileClient(file[0].originalname);
  //     console.log(file[0].buffer, "file.buffer");
  //     console.log(this.accountUrl, "accountUrl", this.sasToken, "this.sasToken", this.fileSystemName, "this.fileSystemName", this.directoryName, "this.directoryName", file.originalname, "file.originalname"  );


  //     // const readableStream = await Readable.from(file[0].buffer);
  //     await fileClient.upload(file[0].buffer)
  //     console.log("1");

  //     await fileClient.append(file[0].buffer, 0, file[0].size);
  //     console.log("2", file[0].size);
  //     await fileClient.flush(file[0].size);
  //     console.log("3");

  //     return { message: 'File uploaded successfully', fileName: file[0].originalname, response: init_response.data };
  //   } catch (error) {
  //     throw new Error(`Upload failed: ${error.message}`);
  //   }
  // }
  //march-16
  //   async uploadFile(file: Express.Multer.File) {
  //     file = file[0]
  //     if (!file || !file.buffer) {
  //       throw new HttpException('Invalid file provided', HttpStatus.BAD_REQUEST);
  //     }

  //     // API headers
  //     const headers = {
  //       'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
  //     };

  //     try {
  //       // Initialize the job to get the input storage path
  //       const init_response = await axios.post(
  //         'https://api.sarvam.ai/speech-to-text-translate/job/init',
  //         '',
  //         { headers }
  //       );

  //       if (!init_response.data.input_storage_path) {
  //         throw new HttpException('No input storage path provided', HttpStatus.BAD_REQUEST);
  //       }

  //       this.updateUrl(init_response.data.input_storage_path);

  //       // Ensure Azure credentials are set
  //       if (!this.accountUrl || !this.fileSystemName || !this.directoryName) {
  //         throw new Error('Azure Data Lake URL is not set');
  //       }

  //       console.log("Uploading to Azure Data Lake...");

  //       // Create Azure DataLake client
  //       const serviceClient = new DataLakeServiceClient(`${this.accountUrl}?${this.sasToken}`);
  //       const fileSystemClient = serviceClient.getFileSystemClient(this.fileSystemName);
  //       const directoryClient = fileSystemClient.getDirectoryClient(this.directoryName);
  //       console.log(this.directoryName, "directoryName", directoryClient, "directoryClient");

  //       await directoryClient.createIfNotExists(); 
  //       console.log(directoryClient, "newwwdirectoryClient");

  //       const fileClient = directoryClient.getFileClient(file.originalname);

  //       console.log("File details:", {
  //         fileName: file.originalname,
  //         fileSize: file.size,
  //         accountUrl: this.accountUrl,
  //         fileSystemName: this.fileSystemName,
  //         directoryName: this.directoryName,
  //       });

  //       // Delete existing file if it exists (to prevent conflicts)
  //       // await fileClient.deleteIfExists();
  //      const a = await fileClient.create();
  //      console.log(a, "a");

  //       console.log(file.buffer, "file.buffer");

  //       // Append the file buffer
  //       const b = await fileClient.append(file.buffer, 0, file.size);
  //       console.log(b, "b");

  //       // Flush the file to finalize the upload
  //       const c = await fileClient.flush(file.size);
  //       console.log(c, "c");

  //       try {
  //         const properties = await fileClient.getProperties();
  // console.log(`File successfully uploaded: Size - ${properties.contentLength} bytes`);
  //       } catch (error) {
  //         console.log(error,"upladed successfully");

  //       }

  //       console.log("Upload successful!");

  //       return {
  //         message: 'File uploaded successfully',
  //         fileName: file.originalname,
  //         response: init_response.data,
  //       };

  //     } catch (error) {
  //       console.error("Upload failed:", error.message);
  //       console.log("poiuytrew",error,"[[]][[]]");

  //       throw new Error(`Upload failed: ${error.message}`);
  //     }
  //   }
  async uploadFile(file: Express.Multer.File) {
    file = file[0]
    if (!file || !file.buffer) {
      throw new HttpException('Invalid file provided', HttpStatus.BAD_REQUEST);
    }

    const headers = {
      'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
    };

    try {
      const initJob = await axios.post(
        'https://api.sarvam.ai/speech-to-text-translate/job/init',
        '',
        { headers }
      );

      console.log("Debug!!!");
      console.log("JOB initialized......")
      console.log(initJob.data)

      if (!initJob.data.input_storage_path) {
        throw new HttpException('No input storage path provided', HttpStatus.BAD_REQUEST);
      }

      const client = new SarvamClient(initJob.data.input_storage_path);
      // client.uploadFiles([file]);

      const serviceClient = new DataLakeServiceClient(`${this.accountUrl}?${this.sasToken}`);
      const fileSystemClient = serviceClient.getFileSystemClient(this.fileSystemName);


      const directoryClient = fileSystemClient.getDirectoryClient(this.directoryName);

      await directoryClient.createIfNotExists();
      const fileClient = directoryClient.getFileClient(file.originalname);

      await fileClient.create();
      await fileClient.append(file.buffer, 0, file.size);
      console.log(file.buffer, "file.buffer");

      await fileClient.flush(file.size);

      return {
        message: 'File uploaded successfully',
        fileName: file.originalname,
        response: initJob.data,
      };
    } catch (error) {
      console.error("Upload failed:", error.message);
      throw new Error(`Upload failed: ${error.message}`);
    }
  }

  //   async getFormData(file: Express.Multer.File) {

  //     let transcriptionText = ''
  //     const form = new FormData();
  //     form.append("file", file.buffer, {
  //       filename: file.originalname,
  //       contentType: file.mimetype,
  //     });

  //     form.append("model", "saaras:v1");
  //     const headers = {
  //       'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
  //       ...form.getHeaders(),
  //     };
  //     const response = await axios.post('https://api.sarvam.ai/speech-to-text-translate', form, { headers });
  //     transcriptionText += response.data.transcript
  //     try {
  //       const messages = [
  //         {
  //           role: 'user', content: `This is an example json structure where 
  // Transcript : ${transcriptionText} 
  //  and json is 
  //  {
  // "firstname": "kannagi",
  // "lastname": "K", 
  // "password": "psd@2025", 
  // "confirm-password": "psd@2025",
  // "dob": 2001-01-01, // date of birth mentioned in the transcript in the given format
  // "gender": "female", 
  // "state": "TamilNadu",
  // "district": "sivagangai",
  // "area-belonged": "Urban", // if area belonged mentioned in the transcript
  // "youthtype": "NSS", // if youth type mentioned in the transcript
  // "sports": "Cricket",
  // "is_willing_for_khelo_India_Talent_hunt": 0 // if willing for khelo India talent hunt mentioned in the transcript if nothing is mentioned make it 0
  // }
  //  give me the json with the keys mentioned in the example for only the fields which are mentioned in the transcript, and ignore the fields which are not mentioned in the transcript.if the audio file doesn't have any relevant data, then just return an empty json object like this: {}
  // Only give the JSON objects, no other explanation needed.`,
  //         }
  //       ];

  //       const headers = {
  //         'x-api-key': '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',
  //         'anthropic-version': '2023-06-01',
  //         'Content-Type': 'application/json',
  //       };
  //       const anthropicData = {
  //         model: 'claude-3-5-sonnet-20241022',
  //         max_tokens: 8192,
  //         messages: messages,
  //       };
  //       const response = await axios.post('https://api.anthropic.com/v1/messages', anthropicData, { headers });
  //       let summa = await response.data.content[0].text
  //       let dongri = JSON.parse(summa)
  //       return dongri;
  //     } catch (error) {
  //       throw new Error(error);
  //     }

  //   }

  //promt modified

  async getFormData(file: Express.Multer.File) {

    let transcriptionText = ''
    const form = new FormData();
    form.append("file", file.buffer, {
      filename: file.originalname,
      contentType: file.mimetype,
    });

    form.append("model", "saaras:v1");
    const headers = {
      'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
      ...form.getHeaders(),
    };
    const response = await axios.post('https://api.sarvam.ai/speech-to-text-translate', form, { headers });
    transcriptionText += response.data.transcript
    try {
      const messages = [
        {
          role: 'user',
          content: `Extract fields from this transcript: "${transcriptionText}".
Return a JSON with only the mentioned fields among:
{
"firstname": "kannagi",
"middlename": "", // if middle name is not mentioned, leave it empty
"lastname": "K",
"username": "kannagi.k", 
"password": "psd@2025",
"confirm-password": "psd@2025",
"email":"kannagi@gmail.com", 
"mobile_number": "9876543210", 
"blood_group": "O+", 
"is_covid_vaccinated": 1, // 0 for no and 1 for yes
"dob": 13-06-2001,
"gender": "female",
"state": "TamilNadu",
"district": "sivagangai",
"pincode":"600011",
"address":"123, Main Street, Sivagangai",
"area-belonged": "Urban",
"youthtype": "NSS",
"sports": "Cricket",
"is_willing_for_khelo_India_Talent_hunt": 0
"area_of_interest":"singing, dancing", // if there are multiple areas of interest, separate them with commas
"subarea_of_interest":"karnatik music, bharatanatyam", // if there are multiple subareas of interest, separate them with commas
"education_type": "",
"institute_type":"college",
"school_district":,
"course_name":"",
"board_name":"",
"student_unique_identifier":"",
"division":"",
"school_state":"",
"school_name":"",
"education_status":"",
"year_of_passing":"",//only year
"student_unique_identifier_value":"",
"obtained_percentage":"",
"languages":"tamil,english",// if there are multiple languages, separate them with commas
"professional_summary_description":"",
"professional_summary_skills":"",// separate multiple skills with commas
"job_title":"",
"company":"",
"location_state":"",
"location_district":"",
"start_date":"",
"end_date":"",
"currently_working_in_this_role":0,0 for no and 1 for yes
"description":"",
"tools":"", // separate multiple tools with commas,
"professional_introduction_video":"",
"social_links":[{"twitter": "", "linkedin": "", "instagram": "", "youtube": ""}],
}

Rules:
- Omit fields not mentioned in the transcript.
- Format "dob" as YYYY-MM-DD.
- Set "is_willing_for_khelo_India_Talent_hunt" to 0 if not clearly stated.
- If nothing relevant is found, return: {} 
- give only the json don't need any other explanation`
        }
      ];


      const headers = {
        'x-api-key': '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',
        'anthropic-version': '2023-06-01',
        'Content-Type': 'application/json',
      };
      const anthropicData = {
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 8192,
        messages: messages,
      };
      const response = await axios.post('https://api.anthropic.com/v1/messages', anthropicData, { headers });
      let summa = await response.data.content[0].text
      let dongri = JSON.parse(summa)
      return dongri;
    } catch (error) {
      throw new Error(error);
    }

  }


  async getNewFormData(file: Express.Multer.File) {

    let transcriptionText = ''
    const form = new FormData();
    form.append("file", file.buffer, {
      filename: file.originalname,
      contentType: file.mimetype,
    });

    form.append("model", "saaras:v1");
    const headers = {
      'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
      ...form.getHeaders(),
    };
    const response = await axios.post('https://api.sarvam.ai/speech-to-text-translate', form, { headers });
    transcriptionText += response.data.transcript
    try {
      const messages = [
        {
          role: 'user',
          content: `Extract fields from this transcript: "${transcriptionText}".
Return a JSON with only the mentioned fields among:
{
  "household_id": "HH001",
  "survey_date": "2025-06-01",
  "interviewer_name": "John Doe",
  "interviewer_id": "INT123",
  "consent": true,
  "full_name": "Ravi Kumar",
  "sex": "Male",
  "age": 42,
  "education_level": "Graduate",
  "caste": "OBC",
  "marital_status": "Married",
  "occupation": "Farmer",
  "demographic_id": 1,
  "survey_date": "2025-06-01",
  "currently_smokes": true,
  "smoking_type": "Cigarettes",
  "smokes_daily": true,
  "smokes_occasionally": false,
  "age_started_smoking": 20,
  "avg_cigarettes_per_day": 10,
  "quit_smoking": false,
  "smoked_daily_in_past": true,
  "years_since_quit": 0,
  "uses_smokeless_tobacco": false,
  "smokeless_daily": false,
  "smokeless_times_per_day": 0,
  "used_smokeless_in_past": false,
  "used_smokeless_daily_in_past": false,
  "ever_consumed_alcohol": true,
  "consumed_past_12_months": true,
  "frequency_past_12_months": "Weekly",
  "consumed_past_30_days": true,
  "drinking_days_last_30": 5,
  "avg_quantity_per_occasion": "3 pegs",
  "max_pegs_single_occasion": 5,
  "binge_drinking_days": 2,
  "unable_to_stop_freq": "Rarely",
  "failed_responsibilities_freq": "Never",
  "morning_drink_freq": "Never",
  "family_issues_due_to_drinking": "No",
  "fruit_days_per_week": 4,
  "fruit_servings_per_day": 2,
  "veg_days_per_week": 6,
  "veg_servings_per_day": 3,
  "adds_extra_salt": "Sometimes",
  "knows_salt_harmful": true,
  "eats_high_salt_food_freq": "Often",
  "salt_reduction_importance": "High",
  "vigorous_work": true,
  "vigorous_days_per_week": 4,
  "vigorous_minutes_per_day": 45,
  "moderate_work": false,
  "moderate_days_per_week": 0,
  "moderate_minutes_per_day": 0,
  "active_commute": true,
  "commute_days_per_week": 5,
  "commute_minutes_per_day": 30,
  "vigorous_recreation": false,
  "vigorous_recreation_days": 0,
  "vigorous_recreation_minutes": 0,
  "moderate_recreation": true,
  "moderate_recreation_days": 3,
  "moderate_recreation_minutes": 30,
  "sitting_time_minutes": 300,
  "bp_measured": true,
  "diagnosed_bp": true,
  "diagnosed_bp_last_12_months": false,
  "on_bp_medication": true,
  "ayurveda_for_bp": false,
  "ayurveda_treatment_bp": false,
  "family_history_bp": true,
  "blood_sugar_measured": true,
  "diagnosed_diabetes": false,
  "diagnosed_diabetes_last_12_months": false,
  "on_diabetes_medication": false,
  "ayurveda_for_diabetes": false,
  "family_history_diabetes": true,
  "cholesterol_measured": true,
  "diagnosed_cholesterol": false,
  "diagnosed_cholesterol_last_12_months": false,
  "on_cholesterol_medication": false,
  "traditional_remedy_cholesterol": false,
  "heart_attack": false,
  "angina": false,
  "stroke": false,
  "on_aspirin": false,
  "on_statins": false,
  "family_history_heart_disease": true,
  "visited_doctor": true,
  "advised_stop_tobacco": true,
  "advised_reduce_salt": true,
  "advised_fruit_veg": true,
  "advised_reduce_fat": false,
  "advised_physical_activity": true,
  "advised_weight_control": false,
  "cervical_screening": false,
  "breast_screening": false,
  "fasting_blood_sugar": "120 mg/dL",
  "total_cholesterol": "180 mg/dL",
  "hdl_cholesterol": "50 mg/dL",
  "ldl_cholesterol": "110 mg/dL",
  "triglycerides": "150 mg/dL",,
  "height" : "170 cm",
  "weight": "70 kg",
  "bmi": 24.2,
  "waist_circumference": "85 cm",
  "hip_circumference": "95 cm",
  "waist_to_hip_ratio": 0.89,
  "bp_reading_1: "120/80 mmHg",
  "bp_reading_2": "125/82 mmHg",
  "bp_reading_3": "118/78 mmHg",
  "bp_average": "122/80 mmHg",
  "heart_rate_reading_1": 72,
  "heart_rate_reading_2": 75,
  "heart_rate_reading_3": 70,
  "heart_rate_average": 72.3,
  "date" : "2025-06-01",
  "time": "10:30 AM",
  "participant_religion":"Buddhism",
  "approximate_monthly_house_hold_income":"2 lakhs",
  "participant_mobile_no":"7092327667",
  "address":"Dubai mainroad,Dubai kurukkusandhu,Dubai",
  "member_of_family_have_high_bp":"Thatha",
  "member_of_family_have_high_diabetes":"Patti",
  "member_of_family_have_heart_disease":"Patti",
  "current_remedy_for_high_cholestrol_status":"no",
  "change_of_lifestyle_advice_in_past_one_year":"yes",
  "pulse_rate":"72bpm",
  "post_prandial_blood_glucose":"200 mg/dL",
  "HbA1c_percentage":5.7,
  "has_quit_smoking":"yes"
}


Rules:
- Omit fields not mentioned in the transcript.
- Format "dob" as YYYY-MM-DD.
- If nothing relevant is found, return: {} 
- give only the json don't need any other explanation`
        }
      ];


      const headers = {
        'x-api-key': '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',
        'anthropic-version': '2023-06-01',
        'Content-Type': 'application/json',
      };
      const anthropicData = {
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 8192,
        messages: messages,
      };
      const response = await axios.post('https://api.anthropic.com/v1/messages', anthropicData, { headers });
      let summa = await response.data.content[0].text
      let dongri = JSON.parse(summa)
      return dongri;
    } catch (error) {
      console.log(error.response.data,"adfadsf");
      
      throw new Error(error);
    }

  }

  //claude-haiku

  // async getFormData(file: Express.Multer.File) {
  //   let transcriptionText = '';


  //   const form = new FormData();
  //   form.append("file", file.buffer, {
  //     filename: file.originalname,
  //     contentType: file.mimetype,
  //   });
  //   form.append("model", "saaras:v1");

  //   const transcribeHeaders = {
  //     'api-subscription-key': '7cb54b7a-4b41-4e59-a117-56cd8e5feb64',
  //     ...form.getHeaders(),
  //   };

  //   const transcriptionRes = await axios.post(
  //     'https://api.sarvam.ai/speech-to-text-translate',
  //     form,
  //     { headers: transcribeHeaders }
  //   );

  //   transcriptionText = transcriptionRes.data.transcript;


  //   try {
  //     const messages = [
  //       {
  //         role: 'user',
  //         content: `Extract fields from this transcript: "${transcriptionText}".
  // Return a JSON with only the mentioned fields among:
  // { "firstname": "", "lastname": "", "password": "", "confirm-password": "", "dob": "", "gender": "", "state": "", "district": "", "area-belonged": "", "youthtype": "", "sports": "", "is_willing_for_khelo_India_Talent_hunt": 0 }

  // Rules:
  // - Omit fields not mentioned in the transcript.
  // - Format "dob" as YYYY-MM-DD.
  // - Set "is_willing_for_khelo_India_Talent_hunt" to 0 if not clearly stated.
  // - If nothing relevant is found, return: {}`
  //       }
  //     ];

  //     const aiHeaders = {
  //       'x-api-key': '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',
  //       'anthropic-version': '2023-06-01',
  //       'Content-Type': 'application/json',
  //     };

  //     const anthropicData = {
  //       model: 'claude-3-haiku-20240307', 
  //       max_tokens: 750, 
  //       messages,
  //     };

  //     const aiRes = await axios.post('https://api.anthropic.com/v1/messages', anthropicData, {
  //       headers: aiHeaders,
  //     });

  //     const result = JSON.parse(aiRes.data.content[0].text);
  //     return result;

  //   } catch (err) {
  //     console.error('Claude API Error:', err.message);
  //     return {};
  //   }
  // }

  async categorizeWithAshwinAI(transcriptionText: string, opd_id: any, hospital_id: any) {
  
    const headers = {"X-API-Key" :'f1e51d152ee82d6201a347736cb3bd5c80c3135a3001725a63b999c61d384da9'}
console.log("oiuytrew",headers);

    try {
      const response = await axios.get(`https://api-ashwin.plenome.com/medical_report?transcript_id=${transcriptionText}`, {headers: headers})
 console.log(1,response.data);
       console.log(response.status, "response.data");


      let summa = await response.data.content[0].text
console.log(2);

      let dongri = await JSON.parse(summa)

console.log(3);



      const uniqueclinical_notes_chiefcomplaints = dongri.clinical_notes.chiefComplaintsBasic.filter((item, index, self) =>
        index === self.findIndex((t) =>
          t.complaint_name.toLocaleLowerCase() === item.complaint_name.toLocaleLowerCase()
        )
      );
      dongri.clinical_notes.chiefComplaintsBasic = uniqueclinical_notes_chiefcomplaints
      const post_clinical_notes = await this.clinicalNotesService.create(dongri.clinical_notes)

      const postVitals = await this.vitalsService.create(dongri.vitals, opd_id, hospital_id)
      const uniquePrescriptions = dongri.prescription.filter((item, index, self) =>
        index === self.findIndex((t) =>
          t.medicine_name.toLowerCase() === item.medicine_name.toLowerCase()
        )
      );

      for (const a of uniquePrescriptions) {
        const post_prescription = await this.PrescriptionService.create(a)


      }

      return response.data;
      // let PreviewResponse = await this.previewService.findAll(opd_id, hospital_id)
      // return PreviewResponse
    } catch (error) {
      // console.error('Error categorizing with Anthropic:', error);

      if (error.response) {
        // console.error('Anthropic API Error Response:', error.response.data);
      } else if (error.request) {
        // console.error('Anthropic API No Response:', error.request);
      } else {
        // console.error('General Error:', error.message);
      }
console.log(error,"daaaaaaaaaaaaaaaata");

      throw new Error('Failed to categorize the transcription text.');
    }
  }

}