import requests
import threading
import time
import base64
import json

# --- Configuration ---
BASE_URL = "https://voice-agent.caprover.al-arcade.com"
STUDENT_ID = "student_001"

# Define three different requests for the SAME student
REQUESTS = {
    "req1": "What is photosynthesis?",
    "req2": "Tell me about gravity.",
    "req3": "How do penguins stay warm?"
}

# Thread-safe dictionary to store results
final_results = {}
lock = threading.Lock()

def run_full_cycle(request_name, question):
    """
    Simulates a full user interaction: POST a question, then immediately GET the audio.
    """
    try:
        # --- Step 1: POST the chat message ---
        chat_url = f"{BASE_URL}/chat"
        chat_payload = {'student_id': STUDENT_ID, 'text': question}
        
        # We don't print here to keep the final report clean
        chat_response = requests.post(chat_url, data=chat_payload)
        chat_response.raise_for_status()
        
        # --- Step 2: GET the audio response ---
        # A short, realistic delay as if the user is waiting for the POST to finish
        time.sleep(1) 
        get_url = f"{BASE_URL}/get-audio-response?student_id={STUDENT_ID}"
        
        audio_response = requests.get(get_url)
        audio_response.raise_for_status()
        
        encoded_text = audio_response.headers.get('X-Response-Text')
        if not encoded_text:
            raise ValueError("X-Response-Text header was missing.")

        decoded_text = base64.b64decode(encoded_text).decode('utf-8')

        # Safely store the successful result
        with lock:
            final_results[request_name] = {
                "request": question,
                "response": decoded_text,
                "status": "✅ SUCCESS"
            }

    except Exception as e:
        with lock:
            final_results[request_name] = {
                "request": question,
                "error": str(e),
                "status": "❌ FAILED"
            }

if __name__ == "__main__":
    print(f"--- Starting 'Impatient User' test for student '{STUDENT_ID}' ---")
    print("Sending 3 requests in rapid succession...")
    
    threads = []
    
    # Create and start a thread for each request
    for name, q in REQUESTS.items():
        thread = threading.Thread(target=run_full_cycle, args=(name, q))
        threads.append(thread)
        thread.start()
        # A very short delay to ensure they are sent almost at the same time
        time.sleep(0.1)

    # Wait for all threads to complete
    for thread in threads:
        thread.join()
        
    print("\n" + "="*50)
    print("---           FINAL TEST REPORT           ---")
    print("="*50 + "\n")
    
    # Print the final report
    for req_name in REQUESTS.keys():
        result = final_results.get(req_name, {})
        
        print(f"Request: '{result.get('request', 'N/A')}'")
        print(f"Status:  {result.get('status', 'UNKNOWN')}")
        
        if "error" in result:
            print(f"  -> Error: {result.get('error')}")
        else:
            print(f"  -> Response: '{result.get('response', '')[:80]}...'") # Print a snippet
        
        print("-" * 50)