import requests
from .text_processor import process_for_podcast

def text_to_speech(text, api_key):
    # Use the enhanced text processor
    cleaned_text = process_for_podcast(text)
    
    url = "https://api.elevenlabs.io/v1/text-to-speech"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "text": cleaned_text,  # Use cleaned text instead of original
        "voice": "en_us_male",  # Specify the desired voice
        "output_format": "mp3"  # Specify the desired output format
    }

    response = requests.post(url, headers=headers, json=data)

    if response.status_code == 200:
        audio_content = response.content
        with open("podcast_episode.mp3", "wb") as audio_file:
            audio_file.write(audio_content)
        return "podcast_episode.mp3"
    else:
        raise Exception(f"Error: {response.status_code}, {response.text}")