import requests
import json
from pathlib import Path
import time

# Configuration
API_BASE_URL = "http://localhost:8000/api/dialog"
ENDPOINT_URL = f"{API_BASE_URL}/generate"

# Define project root relative to this test script (assuming it's in backend/)
PROJECT_ROOT = Path(__file__).resolve().parent
GENERATED_DIALOGS_DIR = PROJECT_ROOT / "tts_generated_dialogs"

DIALOG_PAYLOAD = {
    "output_base_name": "test_dialog_from_script",
    "dialog_items": [
        {
            "type": "speech",
            "speaker_id": "90fcd672-ba84-441a-ac6c-0449a59653bd", # Correct UUID for dummy_speaker
            "text": "This is a test from the Python script. One, two, three.",
            "exaggeration": 1.5,
            "cfg_weight": 4.0,
            "temperature": 0.5
        },
        {
            "type": "silence",
            "duration": 0.5
        },
        {
            "type": "speech",
            "speaker_id": "90fcd672-ba84-441a-ac6c-0449a59653bd",
            "text": "Testing complete. All systems nominal."
        },
        {
            "type": "speech",
            "speaker_id": "non_existent_speaker", # Test case for invalid speaker
            "text": "This should produce an error for this segment."
        },
        {
            "type": "silence",
            "duration": 0.25 # Changed to valid duration
        }
    ]
}

def run_test():
    print(f"Sending POST request to: {ENDPOINT_URL}")
    print("Payload:")
    print(json.dumps(DIALOG_PAYLOAD, indent=2))
    print("-" * 50)

    try:
        start_time = time.time()
        response = requests.post(ENDPOINT_URL, json=DIALOG_PAYLOAD, timeout=120) # Increased timeout for TTS processing
        end_time = time.time()
        
        print(f"Response received in {end_time - start_time:.2f} seconds.")
        print(f"Status Code: {response.status_code}")
        print("-" * 50)
        
        if response.content:
            try:
                response_data = response.json()
                print("Response JSON:")
                print(json.dumps(response_data, indent=2))
                print("-" * 50)

                if response.status_code == 200:
                    print("Test PASSED (HTTP 200 OK)")
                    concatenated_url = response_data.get("concatenated_audio_url")
                    zip_url = response_data.get("zip_archive_url")
                    temp_dir = response_data.get("temp_dir_path")

                    if concatenated_url:
                        print(f"Concatenated audio URL: http://localhost:8000{concatenated_url}")
                    if zip_url:
                        print(f"ZIP archive URL: http://localhost:8000{zip_url}")
                    if temp_dir:
                        print(f"Temporary segment directory: {temp_dir}")
                    
                    print("\nTo verify, check the generated files in:")
                    print(f"  Concatenated/ZIP: {GENERATED_DIALOGS_DIR}")
                    print(f"  Individual segments (if not cleaned up): {temp_dir}")
                else:
                    print(f"Test FAILED (HTTP {response.status_code})")
                    if response_data.get("detail"):
                        print(f"Error Detail: {response_data.get('detail')}")

            except json.JSONDecodeError:
                print("Response content is not valid JSON:")
                print(response.text)
                print("Test FAILED (Invalid JSON Response)")
        else:
            print("Response content is empty.")
            print(f"Test FAILED (Empty Response, HTTP {response.status_code})")

    except requests.exceptions.ConnectionError as e:
        print(f"Connection Error: {e}")
        print("Test FAILED (Could not connect to the server. Is it running?)")
    except requests.exceptions.Timeout as e:
        print(f"Request Timeout: {e}")
        print("Test FAILED (The request timed out. TTS processing might be too slow or stuck.)")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        print("Test FAILED (Unexpected error)")

def test_generate_line_speech():
    url = f"{API_BASE_URL}/generate_line"
    payload = {
        "type": "speech",
        "speaker_id": "90fcd672-ba84-441a-ac6c-0449a59653bd",  # Correct UUID for dummy_speaker
        "text": "This is a per-line TTS test.",
        "exaggeration": 1.0,
        "cfg_weight": 2.0,
        "temperature": 0.8
    }
    print(f"\nTesting /generate_line with speech item: {payload}")
    response = requests.post(url, json=payload)
    print(f"Status: {response.status_code}")
    try:
        data = response.json()
        print(f"Response: {json.dumps(data, indent=2)}")
        if response.status_code == 200 and "audio_url" in data:
            print("Speech line test PASSED.")
        else:
            print("Speech line test FAILED.")
    except Exception as e:
        print(f"Speech line test FAILED: {e}")

def test_generate_line_silence():
    url = f"{API_BASE_URL}/generate_line"
    payload = {
        "type": "silence",
        "duration": 1.25
    }
    print(f"\nTesting /generate_line with silence item: {payload}")
    response = requests.post(url, json=payload)
    print(f"Status: {response.status_code}")
    try:
        data = response.json()
        print(f"Response: {json.dumps(data, indent=2)}")
        if response.status_code == 200 and "audio_url" in data:
            print("Silence line test PASSED.")
        else:
            print("Silence line test FAILED.")
    except Exception as e:
        print(f"Silence line test FAILED: {e}")

if __name__ == "__main__":
    run_test()
    test_generate_line_speech()
    test_generate_line_silence()
