import json
from app import create_app
from app.models.progress import Progress
from app.models.topic import Topic
from app.models.user import User

app = create_app()

with app.app_context():
    student_id = 3
    student = User.query.get(student_id)
    print(f"Checking student: {student.username} (ID: {student_id})")
    
    # Get all progress for this student
    progress_records = Progress.query.filter_by(student_id=student_id).all()
    print(f"Found {len(progress_records)} progress records")
    
    # Calculate statistics
    comprehension_scores = []
    speaking_scores = []
    
    print("\nProgress Details:")
    print("=" * 80)
    for p in progress_records:
        topic = Topic.query.get(p.topic_id)
        print(f"Topic: {topic.title} (ID: {p.topic_id})")
        print(f"  Speaking completed: {bool(p.speaking_completed)}")
        print(f"  Raw speaking_scores: {p.speaking_scores}")
        
        if p.speaking_completed and p.speaking_scores:
            try:
                # If it's a string, try to parse it as JSON
                if isinstance(p.speaking_scores, str):
                    speaking_data = json.loads(p.speaking_scores)
                else:
                    speaking_data = p.speaking_scores
                    
                print(f"  Speaking data type: {type(speaking_data)}")
                
                if 'overall' in speaking_data:
                    overall_score = speaking_data['overall']
                    speaking_scores.append(overall_score)
                    print(f"  Overall speaking score: {overall_score}")
                else:
                    print("  No 'overall' key in speaking_scores")
                    print(f"  Available keys: {list(speaking_data.keys()) if isinstance(speaking_data, dict) else 'Not a dictionary'}")
            except Exception as e:
                print(f"  Error processing speaking scores: {str(e)}")
        else:
            print("  No speaking scores or speaking not completed")
    
    print("\nSummary:")
    print("=" * 80)
    print(f"Total speaking scores found: {len(speaking_scores)}")
    print(f"Speaking scores: {speaking_scores}")
    
    if speaking_scores:
        import statistics
        avg_speaking = statistics.mean(speaking_scores)
        print(f"Average speaking score: {avg_speaking}")
    else:
        print("No speaking scores to calculate average")