#!/usr/bin/env python3
"""
验证考试设置功能是否正常工作
"""
import asyncio
import json
import httpx
from datetime import datetime

BASE_URL = "http://localhost:8000"

async def main():
    async with httpx.AsyncClient() as client:
        # 1. 登录获取token
        print("=== 考试设置功能验证 ===\n")
        print("1. 登录管理员账号...")
        login_resp = await client.post(
            f"{BASE_URL}/api/v1/auth/login",
            json={"username": "admin", "password": "Admin123!"}
        )
        login_data = login_resp.json()
        if login_data['code'] != 200:
            print(f"登录失败: {login_data}")
            return
            
        token = login_data["data"]["token"]["access_token"]
        headers = {"Authorization": f"Bearer {token}"}
        print("✓ 登录成功\n")
        
        # 2. 获取课程7的当前考试设置
        print("2. 获取课程7的当前考试设置...")
        get_resp = await client.get(
            f"{BASE_URL}/api/v1/courses/7/exam-settings",
            headers=headers
        )
        get_data = get_resp.json()
        
        if get_data['code'] == 200 and get_data['data']:
            print("✓ 成功获取考试设置")
            current = get_data['data']
            print(f"\n当前设置:")
            print(f"  - 单选题: {current['single_choice_count']}题")
            print(f"  - 多选题: {current['multiple_choice_count']}题")
            print(f"  - 判断题: {current['true_false_count']}题")
            print(f"  - 填空题: {current['fill_blank_count']}题")
            print(f"  - 考试时长: {current['duration_minutes']}分钟")
            print(f"  - 难度等级: {current['difficulty_level']}")
            print(f"  - 是否启用: {'是' if current['is_enabled'] else '否'}")
            print(f"  - 更新时间: {current['updated_at']}")
        else:
            print(f"✗ 获取失败: {get_data}")
            
        # 3. 测试更新功能
        print("\n3. 测试更新考试设置...")
        test_settings = {
            "single_choice_count": 25,
            "multiple_choice_count": 12,
            "true_false_count": 10,
            "fill_blank_count": 6,
            "duration_minutes": 120,
            "difficulty_level": 5,
            "is_enabled": True
        }
        
        update_resp = await client.post(
            f"{BASE_URL}/api/v1/courses/7/exam-settings",
            json=test_settings,
            headers=headers
        )
        update_data = update_resp.json()
        
        if update_data['code'] == 200:
            print("✓ 成功更新考试设置")
            
            # 4. 再次获取验证
            print("\n4. 再次获取验证更新...")
            verify_resp = await client.get(
                f"{BASE_URL}/api/v1/courses/7/exam-settings",
                headers=headers
            )
            verify_data = verify_resp.json()
            
            if verify_data['code'] == 200 and verify_data['data']:
                updated = verify_data['data']
                print("\n更新后的设置:")
                print(f"  - 单选题: {updated['single_choice_count']}题")
                print(f"  - 多选题: {updated['multiple_choice_count']}题")
                print(f"  - 判断题: {updated['true_false_count']}题")
                print(f"  - 填空题: {updated['fill_blank_count']}题")
                print(f"  - 考试时长: {updated['duration_minutes']}分钟")
                print(f"  - 难度等级: {updated['difficulty_level']}")
                print(f"  - 更新时间: {updated['updated_at']}")
                
                # 验证是否正确更新
                all_correct = (
                    updated['single_choice_count'] == test_settings['single_choice_count'] and
                    updated['multiple_choice_count'] == test_settings['multiple_choice_count'] and
                    updated['true_false_count'] == test_settings['true_false_count'] and
                    updated['fill_blank_count'] == test_settings['fill_blank_count'] and
                    updated['duration_minutes'] == test_settings['duration_minutes'] and
                    updated['difficulty_level'] == test_settings['difficulty_level']
                )
                
                if all_correct:
                    print("\n✅ 考试设置功能完全正常！数据能够正确保存和读取。")
                else:
                    print("\n❌ 数据更新不正确！")
            else:
                print(f"✗ 验证失败: {verify_data}")
        else:
            print(f"✗ 更新失败: {update_data}")
            
        # 5. 提示前端检查
        print("\n=== 前端检查建议 ===")
        print("如果前端仍然显示默认值而不是实际保存的值，请检查：")
        print("1. 刷新页面（F5）后是否正确显示")
        print("2. 浏览器控制台是否有错误")
        print("3. Network面板中API请求是否成功")
        print("4. 清除浏览器缓存后重试")

if __name__ == "__main__":
    asyncio.run(main())
