import requests 
import json 
import os
import sys

#worth trying if api will accept full audios but...sadly nooo
#Error: {"detail":{"status":"invalid_audio_duration","message":"We currently only accept audio up to 300 seconds long, but we received an audio file which is 835.63 seconds long, we will extend this limit in the future."}}

XI_API_KEY = os.environ.get("elevenlabs_api_key")  # Your API key for authentication

if(XI_API_KEY is None or len(XI_API_KEY)==0):
    print("Error: elevenlabs_api_key env var not yet set")
    exit(0)

if(len(sys.argv) < 3):
    print("Error: usage: inputfile.mp3  outfile.mp3 [voice_id=TX3LPaxmHKxFdv7VOQHJ]"  )
    exit(0)

#script_name = sys.argv[0]
AUDIO_FILE_PATH = sys.argv[1]
OUTPUT_PATH = sys.argv[2]

if(len(sys.argv)==4):
    VOICE_ID = sys.argv[3]
else:
    VOICE_ID = "TX3LPaxmHKxFdv7VOQHJ"  # Liam for more: https://api.elevenlabs.io/v1/voices
    
#print(f"InFile:{AUDIO_FILE_PATH}")
#print(f"outFile:{OUTPUT_PATH}")


# Define constants for the script
CHUNK_SIZE = 1024  

#AUDIO_FILE_PATH = "C:\\Users\\home\\Desktop\\test.mp3"  # Path to the input audio file
#OUTPUT_PATH = "C:\\Users\\home\\Desktop\\output.mp3"  # Path to save the output audio file

# Construct the URL for the Speech-to-Speech API request
sts_url = f"https://api.elevenlabs.io/v1/speech-to-speech/{VOICE_ID}/stream"

# Set up headers for the API request, including the API key for authentication
headers = {
    "Accept": "application/json",
    "xi-api-key": XI_API_KEY
}

# Set up the data payload for the API request, including model ID and voice settings
# Note: voice settings are converted to a JSON string
data = {
    "model_id": "eleven_english_sts_v2",
    "voice_settings": json.dumps({
        "stability": 0.5,
        "similarity_boost": 0.8,
        "style": 0.0,
        "use_speaker_boost": True
    })
}

# Set up the files to send with the request, including the input audio file
files = {
    "audio": open(AUDIO_FILE_PATH, "rb")
}

# Make the POST request to the STS API with headers, data, and files, enabling streaming response
response = requests.post(sts_url, headers=headers, data=data, files=files, stream=True)

# Check if the request was successful
if response.ok:
    # Open the output file in write-binary mode
    with open(OUTPUT_PATH, "wb") as f:
        # Read the response in chunks and write to the file
        for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
            f.write(chunk)
    # Inform the user of success
    print("OK: Audio stream saved successfully.")
else:
    # Print the error message if the request was not successful
    print("Error: " + response.text)
