import json
import statistics
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 - the correct way
    comprehension_scores = []
    speaking_scores = []
    
    print("\nProgress Details with Updated Logic:")
    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}")
        
        # Extract speaking scores from nested structure
        if p.speaking_completed and p.speaking_scores:
            print(f"  Speaking scores keys: {list(p.speaking_scores.keys())}")
            
            # Each key in speaking_scores is a submission ID
            for submission_id, scores in p.speaking_scores.items():
                print(f"  Submission {submission_id} scores: {scores}")
                if isinstance(scores, dict) and 'overall' in scores:
                    overall_score = scores['overall']
                    speaking_scores.append(overall_score)
                    print(f"  Added overall speaking score: {overall_score}")
        else:
            print("  No speaking scores or speaking not completed")
            
        # Calculate per-record overall score
        overall_score = 0
        if p.speaking_scores:
            # Get the most recent submission (assuming the last key is the most recent)
            submission_ids = list(p.speaking_scores.keys())
            if submission_ids:
                last_submission = submission_ids[-1]
                scores = p.speaking_scores.get(last_submission, {})
                overall_score = scores.get('overall', 0) if isinstance(scores, dict) else 0
                print(f"  Record overall speaking score: {overall_score}")
    
    print("\nSummary:")
    print("=" * 80)
    print(f"Total speaking scores found: {len(speaking_scores)}")
    print(f"Speaking scores: {speaking_scores}")
    
    if speaking_scores:
        avg_speaking = statistics.mean(speaking_scores)
        print(f"Average speaking score: {avg_speaking}")
    else:
        print("No speaking scores to calculate average")