"""
======================================================================
Dynamic Quiz API Cookbook & Test Script
======================================================================

Purpose:
This script serves as a live integration test and a practical guide ("cookbook") 
for using the new Dynamic Quiz API endpoint.

It demonstrates how to request a quiz of a specific size ('n') for a given topic.

----------------------------------------------------------------------
API Endpoint Guide
----------------------------------------------------------------------

Generate a Dynamic Quiz (POST /quiz/dynamic)
---------------------------------------------
This is the primary endpoint for creating quizzes for students. It's designed 
to be both fresh and comprehensive.

How it Works:
1. It intelligently calculates a small number of *new* questions to generate based on 
   the requested quiz size ('count'). This ensures the question bank is always growing.
2. It calls the AI to generate these new, unique questions and saves them to the database.
3. It retrieves ALL available questions for the topic (both old and new).
4. It randomly shuffles this complete list and returns the number of questions the user asked for.

This provides a dynamic, varied quiz experience every time while efficiently expanding 
your question database.

- Method: POST
- URL: [BASE_URL]/quiz/dynamic
- Data Format: Must be sent as `application/x-www-form-urlencoded` (form data).

Parameters (Form Data):
  - grade (int, required): The grade level of the curriculum (e.g., 4).
  - subject (str, required): The subject of the curriculum (e.g., "Science").
  - unit (str, required): The exact name of the unit.
  - concept (str, required): The exact name of the concept.
  - is_arabic (bool, required): Set to `true` for Arabic curriculum, `false` for English.
  - count (int, optional, default=5): The total number of questions you want in the final quiz.

Example Usage (using cURL):
  # Request a quiz of 10 random questions for the topic.
  # This will generate ~3 new questions and then pick 10 from the whole pool.
  curl -X POST [BASE_URL]/quiz/dynamic \
  -F "grade=4" \
  -F "subject=Science" \
  -F "unit=الوحدة الأولى: الأنظمة الحية" \
  -F "concept=المفهوم الأول: التكيف والبقاء" \
  -F "is_arabic=true" \
  -F "count=10"

----------------------------------------------------------------------
How to Run This Script
----------------------------------------------------------------------
1. Ensure your FastAPI server is running.
2. Make sure the BASE_URL variable below is set to your server's address.
3. Run the script from your terminal: python3 simple_dynamic_quiz_test.py
"""

import requests
import json

# The base URL of your API server.
# Change this to "http://localhost:8000" if you are testing locally.
BASE_URL = "https://voice-agent.caprover.al-arcade.com"

def test_dynamic_quiz(grade: int, subject: str, unit: str, concept: str, is_arabic: bool, count: int):
    """
    Calls the /quiz/dynamic endpoint and prints the raw JSON response.
    """
    endpoint = f"{BASE_URL}/quiz/dynamic"
    
    payload = {
        "grade": grade,
        "subject": subject,
        "unit": unit,
        "concept": concept,
        "is_arabic": is_arabic,
        "count": count,
    }

    print(f">> Requesting a dynamic quiz of {count} questions for:")
    print(f"   Topic: Grade {grade} {subject} -> {unit} -> {concept}")
    print(f"   Language: {'Arabic' if is_arabic else 'English'}")
    
    try:
        # Make the POST request with a long timeout to allow for new question generation
        response = requests.post(endpoint, data=payload, timeout=180) 
        
        print(f"\n--- API Response ---")
        print(f"Status Code: {response.status_code}")
        
        # Try to parse and pretty-print the JSON response
        try:
            response_data = response.json()
            print("\nResponse Body (JSON):")
            print(json.dumps(response_data, indent=2, ensure_ascii=False))
        except json.JSONDecodeError:
            print("\nResponse Body (Not JSON):")
            print(response.text)

    except requests.exceptions.RequestException as e:
        print(f"\nFAILED: An error occurred while making the request: {e}")


if __name__ == "__main__":
    print("\n" + "="*50)
    print("STARTING TEST 1: ARABIC DYNAMIC QUIZ")
    print("="*50)
    
    # Updated test data as requested
    arabic_test_data = {
        "grade": 4,
        "subject": "Science",
        "unit": "الوحدة الأولى: الأنظمة الحية",
        "concept": "المفهوم الأول: التكيف والبقاء",
        "is_arabic": True,
        "count": 3
    }
    
    test_dynamic_quiz(**arabic_test_data)

    print("\n" + "="*50)
    print("STARTING TEST 2: ENGLISH DYNAMIC QUIZ")
    print("="*50)
    
    # Updated test data as requested
    english_test_data = {
        "grade": 5,
        "subject": "Science",
        "unit": "Unit 1: Matter and Energy in Ecosystems",
        "concept": "Concept 1.1: Properties of Matter",
        "is_arabic": False,
        "count": 2
    }
    
    test_dynamic_quiz(**english_test_data)

    print("\n" + "="*50)
    print("All tests complete.")
    print("="*50)