#!/usr/bin/env python3
"""
测试成绩报告和错题本API
"""
import requests
import json

BASE_URL = "http://localhost:8000"

# 测试账号token（需要先登录获取）
# 这里假设已经有token，实际使用时需要先登录
TOKEN = ""

def login():
    """登录获取token"""
    response = requests.post(
        f"{BASE_URL}/api/v1/auth/login",
        json={
            "username": "testuser",
            "password": "TestPass123!"
        }
    )
    if response.status_code == 200:
        data = response.json()
        if data.get('code') == 200:
            return data['data']['access_token']
    return None

def test_exam_report(token):
    """测试成绩报告API"""
    print("\n=== 测试成绩报告API ===")
    
    headers = {"Authorization": f"Bearer {token}"}
    
    response = requests.get(
        f"{BASE_URL}/api/v1/exams/statistics/report",
        headers=headers
    )
    
    print(f"状态码: {response.status_code}")
    if response.status_code == 200:
        data = response.json()
        print(f"响应code: {data.get('code')}")
        print(f"响应message: {data.get('message')}")
        
        if data.get('code') == 200:
            report = data.get('data', {})
            print(f"\n概览数据:")
            print(f"  - 平均成绩: {report.get('overview', {}).get('avg_score')}")
            print(f"  - 考试总数: {report.get('overview', {}).get('total_exams')}")
            print(f"  - 及格率: {report.get('overview', {}).get('pass_rate')}")
            
            print(f"\n科目数量: {len(report.get('subjects', []))}")
            print(f"最近考试数量: {len(report.get('recent_exams', []))}")
            
            # 显示第一条最近考试记录
            if report.get('recent_exams'):
                exam = report['recent_exams'][0]
                print(f"\n第一条考试记录:")
                print(f"  - ID: {exam.get('id')}")
                print(f"  - 课程: {exam.get('course_name')}")
                print(f"  - 三轮得分: {exam.get('round_scores')}")
        else:
            print(f"业务错误: {data.get('message')}")
    else:
        print(f"HTTP错误: {response.text}")

def test_mistakes_statistics(token):
    """测试错题统计API"""
    print("\n=== 测试错题统计API ===")
    
    headers = {"Authorization": f"Bearer {token}"}
    
    response = requests.get(
        f"{BASE_URL}/api/v1/exams/mistakes/statistics",
        headers=headers
    )
    
    print(f"状态码: {response.status_code}")
    if response.status_code == 200:
        data = response.json()
        print(f"响应code: {data.get('code')}")
        
        if data.get('code') == 200:
            stats = data.get('data', {})
            print(f"\n错题总数: {stats.get('total')}")
            print(f"按课程统计: {len(stats.get('by_course', []))} 个课程")
            print(f"按题型统计: {len(stats.get('by_type', []))} 种题型")
            print(f"时间统计:")
            print(f"  - 最近一周: {stats.get('by_time', {}).get('week')}")
            print(f"  - 最近一月: {stats.get('by_time', {}).get('month')}")
            print(f"  - 最近三月: {stats.get('by_time', {}).get('quarter')}")
            
            # 显示按课程统计
            if stats.get('by_course'):
                print(f"\n按课程统计详情:")
                for course in stats['by_course'][:3]:
                    print(f"  - {course.get('course_name')}: {course.get('count')}道")
        else:
            print(f"业务错误: {data.get('message')}")
    else:
        print(f"HTTP错误: {response.text}")

def test_mistakes_list(token):
    """测试错题列表API"""
    print("\n=== 测试错题列表API ===")
    
    headers = {"Authorization": f"Bearer {token}"}
    
    # 测试1：查询所有错题（第1页）
    response = requests.get(
        f"{BASE_URL}/api/v1/exams/mistakes/list",
        headers=headers,
        params={"page": 1, "size": 5}
    )
    
    print(f"状态码: {response.status_code}")
    if response.status_code == 200:
        data = response.json()
        print(f"响应code: {data.get('code')}")
        
        if data.get('code') == 200:
            result = data.get('data', {})
            print(f"\n总数: {result.get('total')}")
            print(f"当前页: {result.get('page')}")
            print(f"每页数量: {result.get('size')}")
            print(f"总页数: {result.get('pages')}")
            print(f"本页错题数: {len(result.get('items', []))}")
            
            # 显示前2条错题
            if result.get('items'):
                print(f"\n前2条错题:")
                for item in result['items'][:2]:
                    print(f"  - ID: {item.get('id')}")
                    print(f"    课程: {item.get('course_name')}")
                    print(f"    题型: {item.get('question_type')}")
                    print(f"    题目: {item.get('question_content')[:50]}...")
        else:
            print(f"业务错误: {data.get('message')}")
    else:
        print(f"HTTP错误: {response.text}")

if __name__ == "__main__":
    print("开始测试成绩报告和错题本API...")
    
    # 1. 登录获取token
    print("\n1. 登录获取token...")
    token = login()
    if not token:
        print("❌ 登录失败")
        exit(1)
    print(f"✅ 登录成功，token: {token[:20]}...")
    
    # 2. 测试成绩报告API
    test_exam_report(token)
    
    # 3. 测试错题统计API
    test_mistakes_statistics(token)
    
    # 4. 测试错题列表API
    test_mistakes_list(token)
    
    print("\n\n测试完成！")

