from openai import OpenAI
import json
from .logger import logger
from .audio_utils import AudioUtils


class WhisperAPI:
    def __init__(self, api_key, base_url, model="whisper-1"):
        self.client = OpenAI(api_key=api_key, base_url=base_url)
        self.model = model
        logger.info("Whisper API client initialized")
    
    def transcribe_file_api(self, audio_data, sample_rate=16000, language="ru"):
        """translate audio file via API"""
        try:
            tmp_file_path = AudioUtils.save_audio_to_temp(audio_data, sample_rate)
            if not tmp_file_path:
                return ""
            
            logger.info(f"Transcribing file via API: {tmp_file_path}")
            with open(tmp_file_path, 'rb') as audio_file:
                response = self.client.audio.transcriptions.create(
                    model=self.model,
                    file=audio_file,
                    language=language,
                    response_format="text"
                )
            
            text = response.strip()
            try:
                data = json.loads(text)
                text = data.get("text", "")
                if isinstance(text, str) and text.startswith('{'):
                    inner_data = json.loads(text)
                    text = inner_data.get("text", "")
            except:
                pass
            
            AudioUtils.cleanup_temp_file(tmp_file_path)
            return text
        except Exception as e:
            logger.error(f"Error transcribing file via API: {e}")
            return ""