<?php
defined('ABSPATH') or die("You can't access this file directly.");

if (!class_exists('Google\Cloud\Speech\V2\Client\SpeechClient') ) {
require( QC_VOICEWIDGET_PLUGIN_DIRNAME. '/autoload.php');
}

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Speech\V2\Client\SpeechClient;
use Google\Cloud\Speech\V2\BatchRecognizeRequest;
use Google\Cloud\Speech\V2\BatchRecognizeFileMetadata;
use Google\Cloud\Speech\V2\RecognitionConfig;
use Google\Cloud\Speech\V2\RecognitionFeatures;
use Google\Cloud\Speech\V2\RecognitionOutputConfig;
use Google\Cloud\Speech\V2\InlineOutputConfig;

use Google\Cloud\Speech\V2\AutoDetectDecodingConfig;
use Google\Cloud\Speech\V2\ExplicitDecodingConfig;
use Google\Cloud\Speech\V2\ExplicitDecodingConfig\AudioEncoding;


function qc_voice_stt_transcribe_audio( $file ) {
    // Path to your Google Cloud service account key JSON fil
    $projectId      = get_option('qc_voice_to_speech_stt_project_id');
    $language       = ( get_option('qc_voice_to_speech_stt_lang_code') != '' ? get_option('qc_voice_to_speech_stt_lang_code') : 'en-US' );
    $bucket_name    = get_option('qc_voice_to_speech_stt_bucket_name');

    try {
        
        $project_id = $projectId;
        //$bucket_name = 'gcp_audio_to_text_bucket_1';
        
        // 1. Decode the JSON String provided in the UI
        //$json_key_content = stripslashes($_POST['json_key']);
        $key_data = json_decode(get_option('qc_voice_to_speech_stt_private_key'), true);


        $auth_config = [
            'projectId' => $project_id,
            'keyFile'   => $key_data 
        ];

        // 2. Initialize Storage (Uploads file to GCS)
        $storage = new StorageClient($auth_config);
        $bucket = $storage->bucket($bucket_name);
        
        $file_name = 'stt-' . time() . '-' . $file['name'];
        $object = $bucket->upload(fopen($file['tmp_name'], 'r'), ['name' => $file_name]);
        $gcs_uri = "gs://{$bucket_name}/{$file_name}";

        // 3. Initialize Speech Client (V2)
        $speechClient = new SpeechClient([
            'credentials' => $key_data
        ]);

        //$location = 'us-central1'; // Adjust to your bucket location
        $location = 'global'; // Adjust to your bucket location
        $recognizer = "projects/{$project_id}/locations/{$location}/recognizers/_";
        
        $explicitConfig = (new ExplicitDecodingConfig())
            ->setEncoding(AudioEncoding::MP3)
            ->setSampleRateHertz(16000)
            ->setAudioChannelCount(1);
        
        
        $config = (new RecognitionConfig())
            ->setAutoDecodingConfig(new AutoDetectDecodingConfig())
            ->setLanguageCodes([$language]) // V2 uses an array for language codes
            ->setModel('long'); // 'long' or 'chirp' are recommended for V2

        $fileMetadata = (new BatchRecognizeFileMetadata())->setUri($gcs_uri);
            
        $outputConfig = (new RecognitionOutputConfig())
            ->setInlineResponseConfig(new InlineOutputConfig());

        $request = (new \Google\Cloud\Speech\V2\BatchRecognizeRequest())
            ->setRecognizer($recognizer)
            ->setConfig($config)
            ->setFiles([$fileMetadata])
            ->setRecognitionOutputConfig($outputConfig);

        // 4. Start Batch Operation
        $operation = $speechClient->batchRecognize($request);
        $status = "Authentication Successful. Processing audio...";
        
        // Wait for results (Polled synchronously for simplicity)
        $operation->pollUntilComplete(['pollIntervalMillis' => 10000]);
        
        $transcript = '';
        if ($operation->operationSucceeded()) {
            $response = $operation->getResult(); // BatchRecognizeResponse
            $fileResultsMap = $response->getResults();

            foreach ($fileResultsMap as $gcsUri => $fileResult) {
                // 1. Get the InlineResult object
                $inlineResult = $fileResult->getInlineResult();
                
                if ($inlineResult && $inlineResult->hasTranscript()) {
                    // 2. Access the BatchRecognizeResults object
                    $transcriptObj = $inlineResult->getTranscript();
                    
                    // 3. NOW call getResults() on the transcript object
                    $results = $transcriptObj->getResults(); 

                    foreach ($results as $result) {
                        // 4. Get the alternatives (SpeechRecognitionAlternative)
                        $alternatives = $result->getAlternatives();
                        if (count($alternatives) > 0) {
                            // Use the first alternative (highest confidence)
                            $transcript .= $alternatives[0]->getTranscript() . ' ';
                        }
                    }
                }
            }
        }

        // 5. Cleanup: Delete from GCS immediately after transcription
        $object->delete();

        return $transcript;


    } catch ( Exception $e ) {
        // Log the error
        error_log( "Google STT Error: " . $e->getMessage() );
        return false;
    }
}

