"""
======================================================================
MCQ API Cookbook & Test Script
======================================================================

Purpose:
This script serves as both a live integration test and a practical guide ("cookbook") 
for using the Multiple-Choice Question (MCQ) generation and retrieval API endpoints.

It demonstrates how to:
  1. Generate and store new MCQs for a specific curriculum topic.
  2. Retrieve existing MCQs from the database for that same topic.

----------------------------------------------------------------------
API Endpoints Guide
----------------------------------------------------------------------

There are two main endpoints for the MCQ feature:

1. Generate Questions (POST /mcq/generate)
------------------------------------------
This is the "creator" endpoint. It uses an AI model to generate a new set of questions 
based on the curriculum content stored in the vector database. It then saves these 
new questions to the `mcq_questions` table for future use.

- Method: POST
- URL: [BASE_URL]/mcq/generate
- 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 number of new questions to generate.

Example Usage (using cURL):
  curl -X POST [BASE_URL]/mcq/generate \
  -F "grade=4" \
  -F "subject=Science" \
  -F "unit=الوحدة الأولى: الأنظمة الحية" \
  -F "concept=المفهوم الأول: التكيف والبقاء" \
  -F "is_arabic=true" \
  -F "count=3"


2. Retrieve Questions (GET /mcq)
---------------------------------
This is the "reader" endpoint. It quickly and cheaply retrieves questions that have 
already been generated and stored in the database. It does NOT call the AI model.

- Method: GET
- URL: [BASE_URL]/mcq

Parameters (URL Query Parameters):
  - grade (int, required): The grade level.
  - subject (str, required): The subject.
  - unit (str, required): The unit name.
  - concept (str, required): The concept name.
  - is_arabic (bool, required): `true` for Arabic, `false` for English.
  - limit (int, optional, default=None): The maximum number of questions to retrieve. 
                                         If omitted, it will retrieve ALL questions for that topic.

Example Usage (using cURL):
  # Get the 5 most recent questions for a topic
  curl "[BASE_URL]/mcq?grade=4&subject=Science&unit=...&concept=...&is_arabic=true&limit=5"

  # Get ALL questions for a topic
  curl "[BASE_URL]/mcq?grade=4&subject=Science&unit=...&concept=...&is_arabic=true"


----------------------------------------------------------------------
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 msq_test.py
"""

import requests
import json
import time
from typing import Optional

# The base URL of your API server.
BASE_URL = "https://voice-agent.caprover.al-arcade.com"

def test_mcq_generation(grade: int, subject: str, unit: str, concept: str, is_arabic: bool, count: int):
    """
    Tests the POST /mcq/generate endpoint.
    """
    endpoint = f"{BASE_URL}/mcq/generate"
    
    payload = {
        "grade": grade,
        "subject": subject,
        "unit": unit,
        "concept": concept,
        "is_arabic": is_arabic,
        "count": count,
    }

    print(f">> Attempting to GENERATE {count} new questions for:")
    print(f"   Topic: Grade {grade} {subject} -> {unit} -> {concept}")
    print(f"   Language: {'Arabic' if is_arabic else 'English'}")
    
    try:
        response = requests.post(endpoint, data=payload, timeout=120) 
        
        if response.status_code == 200:
            print(f"SUCCESS: API returned status code {response.status_code}")
            data = response.json()
            print(f"   Message: {data.get('message')}")
            
            if 'questions' in data and data['questions']:
                print("\n   --- Details of Generated Questions ---")
                for i, q in enumerate(data['questions'], 1):
                    print(f"   {i}. Question: {q['question_text']}")
                    print(f"      Correct:   {q['correct_answer']}")
                    print(f"      Wrong 1:   {q['wrong_answer_1']}")
                    print(f"      Wrong 2:   {q['wrong_answer_2']}")
                    print(f"      Wrong 3:   {q['wrong_answer_3']}\n")
            return True
        else:
            print(f"FAILED: API returned status code {response.status_code}")
            try:
                error_data = response.json()
                print(f"   Error Detail: {error_data.get('detail', 'No detail provided.')}")
            except json.JSONDecodeError:
                print(f"   Response was not valid JSON: {response.text}")
            return False

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


def test_mcq_retrieval(grade: int, subject: str, unit: str, concept: str, is_arabic: bool, limit: Optional[int]):
    """
    Tests the GET /mcq endpoint with detailed output.
    """
    endpoint = f"{BASE_URL}/mcq"
    
    params = {
        "grade": grade,
        "subject": subject,
        "unit": unit,
        "concept": concept,
        "is_arabic": is_arabic,
    }
    if limit is not None:
        params["limit"] = limit
    
    limit_str = f"up to {limit}" if limit is not None else "ALL"
    print(f">> Attempting to RETRIEVE {limit_str} stored questions for the same topic...")

    try:
        response = requests.get(endpoint, params=params, timeout=30)
        
        if response.status_code == 200:
            print(f"SUCCESS: API returned status code {response.status_code}")
            data = response.json()
            print(f"   Found {data.get('count')} stored questions in the database.")
            
            if 'questions' in data and data['questions']:
                print("\n   --- Details of Retrieved Questions ---")
                for i, q in enumerate(data['questions'], 1):
                    print(f"   {i}. Question: {q['question_text']}")
                    print(f"      Correct:   {q['correct_answer']}")
                    print(f"      Wrong 1:   {q['wrong_answer_1']}")
                    print(f"      Wrong 2:   {q['wrong_answer_2']}")
                    print(f"      Wrong 3:   {q['wrong_answer_3']}\n")
            elif data.get('count') == 0:
                print("   (This is expected if this is the first time generating questions for this topic)")
            return True
        else:
            print(f"FAILED: API returned status code {response.status_code}")
            try:
                error_data = response.json()
                print(f"   Error Detail: {error_data.get('detail', 'No detail provided.')}")
            except json.JSONDecodeError:
                print(f"   Response was not valid JSON: {response.text}")
            return False

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


if __name__ == "__main__":
    print("\n" + "="*50)
    print("STARTING TEST 1: ARABIC MCQ GENERATION & RETRIEVAL")
    print("="*50)
    
    # IMPORTANT: Use actual Unit/Concept names from your database for the best results.
    arabic_test_data = {
        "grade": 4,
        "subject": "Science",
        "unit": "الوحدة الأولى: الأنظمة الحية",
        "concept": "المفهوم الأول: التكيف والبقاء",
        "is_arabic": True,
        "count": 3
    }
    
    generation_successful = test_mcq_generation(**arabic_test_data)
    
    if generation_successful:
        print("-" * 25)
        time.sleep(2)
        test_mcq_retrieval(limit=None, **{k:v for k,v in arabic_test_data.items() if k != 'count'})

    print("\n" + "="*50)
    print("STARTING TEST 2: ENGLISH MCQ GENERATION & RETRIEVAL")
    print("="*50)
    
    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
    }
    
    generation_successful = test_mcq_generation(**english_test_data)
    
    if generation_successful:
        print("-" * 25)
        time.sleep(2)
        test_mcq_retrieval(limit=None, **{k:v for k,v in english_test_data.items() if k != 'count'})

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