import requests
import json
import time

# --- Configuration ---
# The base URL of your running FastAPI application.
# Change this if your app is running on a different host or port.
BASE_URL = "https://voice-agent-v2.caprover.al-arcade.com"

# Define the topic we will use for all tests
TEST_DATA = {
    "curriculum": "EGYPTIAN National",
    "grade": "4th Grade",
    "subject": "Science",
    "unit": "الوحدة الأولى: ما النظام؟",
    "concept": "المفهوم 3.1: الطاقة كنظام",
}

# --- Helper Function to Print Formatted JSON ---
def print_json(data, title=""):
    """
    This function is responsible for printing the entire JSON response.
    `json.dumps` with `indent=2` makes it readable.
    `ensure_ascii=False` correctly displays Arabic characters.
    """
    if title:
        print(f"--- {title} ---")
    
    # This line prints the FULL response data.
    print(json.dumps(data, indent=2, ensure_ascii=False))
    
    print("\n" + "="*50 + "\n")

# --- Test Functions ---

def test_generate_mcqs():
    """Tests the POST /mcq/generate endpoint."""
    print("  Starting test for: POST /mcq/generate")
    
    form_data = {**TEST_DATA, "count": 2, "is_arabic": True}

    try:
        start_time = time.time()
        response = requests.post(f"{BASE_URL}/mcq/generate", data=form_data)
        duration = time.time() - start_time
        
        print(f"Status Code: {response.status_code} (took {duration:.2f} seconds)")
        response.raise_for_status()

        response_data = response.json()

        # >>> THE RESPONSE IS PRINTED RIGHT HERE <<<
        print_json(response_data, "Full Response from /mcq/generate")

        assert response_data["status"] == "success"
        print("✅ Test for /mcq/generate PASSED")

    except requests.exceptions.RequestException as e:
        print(f"❌ Test for /mcq/generate FAILED: An HTTP error occurred: {e}")
        print("--- Raw Response Text ---")
        print(response.text)
    except Exception as e:
        print(f"❌ Test for /mcq/generate FAILED: An error occurred: {e}")
        print("--- Raw Response Text ---")
        print(response.text)


def test_dynamic_quiz():
    """Tests the POST /quiz/dynamic endpoint."""
    print("  Starting test for: POST /quiz/dynamic")
    
    form_data = {**TEST_DATA, "count": 3, "is_arabic": True}

    try:
        start_time = time.time()
        response = requests.post(f"{BASE_URL}/quiz/dynamic", data=form_data)
        duration = time.time() - start_time
        
        print(f"Status Code: {response.status_code} (took {duration:.2f} seconds)")
        response.raise_for_status()

        response_data = response.json()
        
        # >>> THE RESPONSE IS PRINTED RIGHT HERE <<<
        print_json(response_data, "Full Response from /quiz/dynamic")

        assert response_data["status"] == "success"
        
        # Verify that the response is indeed filtered
        if response_data.get("quiz"):
            first_question = response_data["quiz"][0]
            if "curriculum" in first_question:
                 # This is not a failure of the test, but a failure of the API logic.
                 print("⚠️ WARNING: /quiz/dynamic response was NOT filtered. It still contains the 'curriculum' field.")
            else:
                 print("✔️ Verification successful: /quiz/dynamic response is correctly filtered.")

        print("✅ Test for /quiz/dynamic PASSED")

    except requests.exceptions.RequestException as e:
        print(f"❌ Test for /quiz/dynamic FAILED: An HTTP error occurred: {e}")
        print("--- Raw Response Text ---")
        print(response.text)
    except Exception as e:
        print(f"❌ Test for /quiz/dynamic FAILED: An error occurred: {e}")
        print("--- Raw Response Text ---")
        print(response.text)


# --- Main Execution Block ---
if __name__ == "__main__":
    print("Starting MCQ Endpoint Tests...\n")
    # Run the first test
    test_generate_mcqs()
    
    # Run the second test
    test_dynamic_quiz()
    
    print("All tests completed.")