import sys
import os
from app import create_app, db
from app.models.topic import Topic, SpeakingQuestion
from app.models.progress import Progress
from app.models.user import User

app = create_app()

with app.app_context():
    # Get a topic
    topic = Topic.query.first()
    if not topic:
        print("No topics found in database!")
        sys.exit(1)
    
    # Get speaking questions
    questions = topic.speaking_questions
    print(f"Found {len(questions)} speaking questions for topic '{topic.title}':")
    
    for i, q in enumerate(questions):
        print(f"{i+1}. ID: {q.id} - {q.text}")
    
    # Get a student
    student = User.query.filter_by(role='student').first()
    if not student:
        print("No student found in database!")
        sys.exit(1)
    
    # Get or create progress
    progress = Progress.query.filter_by(
        student_id=student.id,
        topic_id=topic.id
    ).first()
    
    if not progress:
        print("No progress found for this student and topic.")
        sys.exit(1)
    
    # Print speaking scores
    if hasattr(progress, 'speaking_scores') and progress.speaking_scores:
        print("\nCompleted questions:")
        for q_id, scores in progress.speaking_scores.items():
            if q_id != 'overall':  # Skip overall score
                q = next((q for q in questions if str(q.id) == q_id), None)
                if q:
                    print(f"Question {q_id}: '{q.text}' - Score: {scores.get('overall', 0)}%")
    else:
        print("\nNo speaking questions completed yet.")
    
    # Find the next question to show
    completed_question_ids = set(progress.speaking_scores.keys()) if progress.speaking_scores else set()
    
    next_question = next(
        (q for q in questions if str(q.id) not in completed_question_ids),
        questions[0] if questions else None
    )
    
    if next_question:
        print(f"\nNext question to show: ID {next_question.id} - '{next_question.text}'")
    else:
        print("\nAll questions have been completed.") 