# This is done

import requests

import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Get the Suno API key from environment variables
SUNO_API_KEY = os.getenv("SUNO_API_KEY")


def request_generation(prompt: str) -> str:
    """
    Generate a song using the Suno API.

    Args:
        prompt (str): Text description of the song to generate

    Returns:
        str: First clip ID or None if request failed
    """
    url = "https://studio-api.prod.suno.com/api/generate/v2-web"

    headers = {
        "Authorization": f"Bearer {SUNO_API_KEY}",
        "Content-Type": "application/json",
    }

    payload = {
        "token": None,
        "gpt_description_prompt": prompt,
        "mv": "chirp-v3-5",
        "prompt": "",
        "metadata": {"create_mode": "simple", "lyrics_model": "remi-v1"},
        "make_instrumental": False,
        "user_uploaded_images_b64": [],
        "generation_type": "TEXT",
    }

    max_retries = 3
    retry_count = 0

    while retry_count < max_retries:
        try:
            response = requests.post(url, json=payload, headers=headers)

            if response.status_code == 200:
                response_data = response.json()
                # Extract first clip ID from the response
                if (
                    "clips" in response_data
                    and isinstance(response_data["clips"], list)
                    and response_data["clips"]
                    and "id" in response_data["clips"][0]
                ):
                    return response_data["clips"][0]["id"]
                else:
                    print(
                        "Unexpected response format: 'clips' array not found or empty"
                    )
                    return None
            else:
                print(f"Error: {response.status_code}")
                print(response.text)

                if retry_count < max_retries - 1:
                    print("Retrying in 5 seconds...")
                    import time

                    time.sleep(5)

                retry_count += 1
        except Exception as e:
            print(f"Exception occurred: {e}")

            if retry_count < max_retries - 1:
                print("Retrying in 5 seconds...")
                import time

                time.sleep(5)

            retry_count += 1

    return None
