from flask import jsonify
from urllib.parse import unquote
from config import db

def get_quiz_details(request, Question, Option, Topic):
    data = request.get_json()
    print("Input Data:", data)

    query = data.get('title')
    # print(query)
    course_id = data.get('course_id')  # Default to 0 if not provided
    topic_id = data.get('topic_id')  # Optional topic_id

    try:
        decoded_query = unquote(query) if query else None

    
    except:
        decoded_query = unquote(query['title']) if query else None

    print("Decoded Query:", decoded_query)

    topic_query = Topic.query
    has_filters = False

    # Apply filter if title query is provided
    if decoded_query and len(decoded_query) > 0:
        partial_query = f"%{decoded_query}%"  # Enable partial matching with wildcards
        topic_query = topic_query.filter(Topic.title.ilike(partial_query))
        has_filters = True
    else:
        # If query is empty, no filter is applied for title
        if course_id:
            topic_query = topic_query.filter(Topic.course_id == course_id)
            has_filters = True

        if topic_id:
            topic_query = topic_query.filter(Topic.id == topic_id)
            has_filters = True

    if not has_filters:
        # If no filters were applied, return all topics
        topic_query = Topic.query.all()

    topics = topic_query
    print("Filtered Topics:", topics)

    organized_quizzes = {}

    for topic in topics:
        print(f"Processing Topic ID {topic.id}: {topic.title}")
        
        results = db.session.query(Question, Option).\
            join(Topic, Question.topic_id == Topic.id).\
            outerjoin(Option, Question.question_id == Option.question_id).\
            filter(Question.topic_id == topic.id).\
            order_by(Question.question_id).\
            all()
        
        print(f"Results for Topic ID {topic.id}:", results)

        topic_id = topic.id
        organized_quizzes[topic_id] = {
            'id': topic.id,
            'course_id': topic.course_id,
            'title': topic.title,
            'description': topic.description or None,
            'content_type': topic.content_type,
            'content_url': topic.content_url or None,
            'order': topic.order,
            'duration_minutes': topic.duration_minutes or None,
            'is_previewable': topic.is_previewable,
            'status': topic.status,
            'created_at': topic.created_at.strftime('%Y-%m-%dT%H:%M:%S') if topic.created_at else None,
            'updated_at': topic.updated_at.strftime('%Y-%m-%dT%H:%M:%S') if topic.updated_at else None,
            'questions': []
        }

        for question, option in results:
            print("Question:", question)
            print("Option:", option)

            existing_question = next((q for q in organized_quizzes[topic_id]['questions'] if q['question_id'] == question.question_id), None)

            if not existing_question:
                existing_question = {
                    'question_id': question.question_id,
                    'question_text': question.question_text,
                    'correct_answer': question.correct_answer,
                    'options': []
                }
                organized_quizzes[topic_id]['questions'].append(existing_question)

            existing_question['options'].append({
                'option_id': option.option_id if option else None,
                'option_text': option.option_text if option else None,
                'is_correct': option.is_correct if option else None
            })

    output = []
    for topic_id, topic_data in organized_quizzes.items():
        output.append({
            'id': topic_data['id'],
            'course_id': topic_data['course_id'],
            'title': topic_data['title'],
            'description': topic_data['description'],
            'content_type': topic_data['content_type'],
            'content_url': topic_data['content_url'],
            'order': topic_data['order'],
            'duration_minutes': topic_data['duration_minutes'],
            'is_previewable': topic_data['is_previewable'],
            'status': topic_data['status'],
            'created_at': topic_data['created_at'],
            'updated_at': topic_data['updated_at'],
            'questions': topic_data['questions']
        })

    print("Final Output:", output)
    return jsonify({'quiz_details': output}), 200
