import care.eka.EkaCareClient;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.Base64;
public class EkascribeIntegrationExample {
    public static void main(String[] args) {
        try {
            // Initialize the client
            EkaCareClient client = new EkaCareClient("your_client_id", "your_client_secret");
            
            // Authenticate
            authenticateClient(client);
            
            // Upload audio files
            String transactionId = "unique_transaction_id";
            String action = "ekascribe-v2";
            uploadAudioFiles(client, transactionId, action);
            
            // NOTE: At this point, wait for the webhook callback
            // This would typically be handled by your web server
            
            // Once webhook is received, fetch results
            // The sessionId would come from the webhook payload
            getTranscriptionResults(client, transactionId, action);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void authenticateClient(EkaCareClient client) throws IOException {
        JsonNode tokenResponse = client.getAuth().login();
        // Extras
        System.out.println("Access Token: " + tokenResponse.get("access_token").asText());
        System.out.println("Refresh Token: " + tokenResponse.get("refresh_token").asText());
        client.setAccessToken(tokenResponse.get("access_token").asText());
        // Refresh token when needed
        JsonNode refreshedTokens = client.getAuth().refreshToken(tokenResponse.get("refresh_token").asText());
        
        // Extras
        System.out.println("New Access Token: " + refreshedTokens.get("access_token").asText());
    }
    
    private static void uploadAudioFiles(EkaCareClient client, String transactionId, String action) throws IOException {
        // Collect all audio files in a list
        List<String> audioFiles = new ArrayList<>();
        audioFiles.add("<full file path>");
        audioFiles.add("<full file path 2>");
        Map<String, Object> extraData = new HashMap<>();
        extraData.put("mode", "dictation");
        extraData.Put("model_type", "lite");
        //Custom keys , you'll get back the exact same in result API
        extraData.put("uhid", "unique_patient_id"); 
        extraData.put("hfid", "unique_health_facility_id");
        // Define the output format for the V2RX action
        Map<String, Object> outputFormat = new HashMap<>();
        outputFormat.put("input_language", Arrays.asList("en-IN", "hi"));
        // output template ids
        Map<String, Object> templateMap1 = new HashMap<>();
        templateMap1.put("template_id", "clinical_notes_template");
        templateMap1.put("language_output", "en-IN");
        // set true if you need codified data (if out supports that)
        templateMap1.put("codification_needed", true);
        
        // Sample second template id
        Map<String, Object> templateMap2 = new HashMap<>();
        templateMap2.put("template_id", "eka_emr_template");
        templateMap2.put("language_output", "en-IN");
        
        // Add both templates to the output_template list
        outputFormat.put("output_template", Arrays.asList(templateMap1, templateMap2));
        
        List<JsonNode> responses = client.getV2RX().upload(audioFiles, transactionId, action, extraData, outputFormat);
        System.out.println("Upload Responses: " + responses.toString());
    }
    
    private static void getTranscriptionResults(EkaCareClient client, String sessionId, String action) throws IOException {
        JsonNode sessionStatus = client.getV2RX().getSessionStatus(sessionId, action);
        System.out.println("Session Status: " + sessionStatus.toPrettyString());
        
        if (sessionStatus.has("data") &&
                sessionStatus.get("data").has("output") &&
                sessionStatus.get("data").get("output").isArray() &&
                sessionStatus.get("data").get("output").size() > 0) {
            JsonNode outputNode = sessionStatus.get("data").get("output");
            Integer step = 0;
            for (JsonNode node : outputNode) {
                if (node.has("value")) {
                    step++;
                    String templateId = node.get("template_id").asText();
                    String templateName = node.get("name").asText();
                    String encodedValue = node.get("value").asText();
                    byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
                    String templateJson = new String(decodedBytes);
                    System.out.println("Template: " + templateName + " (" + templateId + ")");
                    System.out.println("Decoded Data " + step + " :" + templateJson);
                } else {
                    System.out.println("No value found in output node "+ step+ " :"+ node.toPrettyString());
                }
            }
        }
    }
}