<?php

namespace App\Services\FileTools\Transcription;

use Log;

class OpenAIAPIAudioTranscriptor implements IAudioTranscriptor
{

    private function getHeaders(): array
    {
        return [
            'Authorization: ' . (config('llm.api.transcription.token') ? 'Bearer ' . config('llm.api.transcription.token') : ''),
            //'Content-Type: application/json',
        ];
    }

    /**
     * @inheritDoc
     */
    public function transcribe(string $filePath): ?string
    {
        if (!file_exists($filePath)) {
            Log::error("File not found: {$filePath}");
            return null;
        }

        // Make a call to the API with curl
        // Example of working curl command:
        // curl -s "SPEACHES_BASE_URL/v1/audio/transcriptions" -F "file=@/home/ninluc/Downloads/memeSalto/m19.mp3" -F "model=MODEL_ID"
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => config('llm.api.transcription.host') . '/audio/transcriptions',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => [
                'file' => new \CURLFile($filePath),
                'model' => config('llm.models.transcription.name'),
            ],
            CURLOPT_HTTPHEADER => $this->getHeaders(),
        ]);
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($httpCode !== 200) {
            Log::error("Error during transcription: HTTP code {$httpCode} : {$response}");
            return null;
        }
        $responseData = json_decode($response, true);
        return $responseData['text'] ?? null;
    }
}
