from openai import OpenAI
import os
from dotenv import load_dotenv
from config.constants import OPENAI_WHISPER_MODEL_NAME

# Load environment variables
load_dotenv(dotenv_path=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'config', '.env'))

class WhisperSTT:
    def __init__(self):
        self.api_key = os.environ.get('OPENAI_API_KEY')
        if not self.api_key:
            raise ValueError("Missing OPENAI_API_KEY in environment variables.")
        #openai.api_key = self.api_key
        self.client = OpenAI(api_key=self.api_key)

    def transcribe_audio(self, file_path):
        print(f"Transcribing audio file: {file_path}")
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"Audio file not found: {file_path}")
        
        if not os.path.isfile(file_path):
            raise ValueError(f"Invalid file path: {file_path}")

        try:
            with open(file_path, 'rb') as audio_file:
                transcription = self.client.audio.transcriptions.create(
                    model=OPENAI_WHISPER_MODEL_NAME,
                    file=audio_file
                )
                print("Transcription response:", transcription.text)
                #return transcription.text.strip()
                text = getattr(transcription, "text", None)
                if not text:
                    raise ValueError("OpenAI transcription response missing 'text'. Full response: " + str(transcription))
                return text
        # except openai.error.OpenAIError as api_err:
        #     print("OpenAI API error:", str(api_err))
        #     raise
        except Exception as e:
            print("Unexpected error during transcription:", str(e))
            raise
