#!/usr/bin/env python3
"""
测试陪练记录API
"""
import requests
import json
from datetime import datetime, timedelta

# API基础URL
BASE_URL = "http://localhost:8000"

# 测试用户的token（需要先登录获取）
def login(username: str, password: str):
    """登录获取token"""
    response = requests.post(
        f"{BASE_URL}/api/v1/auth/login",
        json={"username": username, "password": password}
    )
    if response.status_code == 200:
        data = response.json()
        if data.get("code") == 200:
            return data["data"]["access_token"]
    print(f"登录失败: {response.text}")
    return None

def test_practice_sessions(token: str, params: dict = None):
    """测试陪练记录列表API"""
    headers = {"Authorization": f"Bearer {token}"}
    
    response = requests.get(
        f"{BASE_URL}/api/v1/practice/sessions/list",
        headers=headers,
        params=params or {}
    )
    
    print(f"\n{'='*60}")
    print(f"请求参数: {params}")
    print(f"响应状态码: {response.status_code}")
    print(f"{'='*60}")
    
    if response.status_code == 200:
        data = response.json()
        print(json.dumps(data, indent=2, ensure_ascii=False))
        
        if data.get("code") == 200:
            result_data = data["data"]
            print(f"\n📊 统计信息:")
            print(f"  - 总记录数: {result_data.get('total')}")
            print(f"  - 当前页码: {result_data.get('page')}")
            print(f"  - 每页数量: {result_data.get('page_size')}")
            print(f"  - 总页数: {result_data.get('pages')}")
            print(f"  - 本页记录数: {len(result_data.get('items', []))}")
            
            if result_data.get('items'):
                print(f"\n📝 前3条记录:")
                for i, item in enumerate(result_data['items'][:3], 1):
                    print(f"  {i}. {item.get('scene_name')} - 评分: {item.get('total_score')} - {item.get('start_time')}")
    else:
        print(f"请求失败: {response.text}")

def test_practice_stats(token: str):
    """测试陪练统计API"""
    headers = {"Authorization": f"Bearer {token}"}
    
    response = requests.get(
        f"{BASE_URL}/api/v1/practice/stats",
        headers=headers
    )
    
    print(f"\n{'='*60}")
    print(f"陪练统计API")
    print(f"{'='*60}")
    
    if response.status_code == 200:
        data = response.json()
        print(json.dumps(data, indent=2, ensure_ascii=False))
    else:
        print(f"请求失败: {response.text}")

if __name__ == "__main__":
    # 测试不同用户
    test_users = [
        ("superadmin", "admin123"),
        ("nurse_001", "password123"),
        ("consultant_001", "password123"),
    ]
    
    for username, password in test_users:
        print(f"\n{'#'*60}")
        print(f"# 测试用户: {username}")
        print(f"{'#'*60}")
        
        # 登录
        token = login(username, password)
        if not token:
            print(f"❌ {username} 登录失败，跳过")
            continue
        
        print(f"✅ {username} 登录成功")
        
        # 测试统计API
        test_practice_stats(token)
        
        # 测试列表API - 无参数
        print(f"\n\n测试场景1: 无参数查询")
        test_practice_sessions(token)
        
        # 测试列表API - 带日期范围
        print(f"\n\n测试场景2: 最近30天")
        today = datetime.now()
        start_date = (today - timedelta(days=30)).strftime("%Y-%m-%d")
        end_date = today.strftime("%Y-%m-%d")
        test_practice_sessions(token, {
            "start_date": start_date,
            "end_date": end_date,
            "page": 1,
            "size": 20
        })
        
        print("\n" + "="*60 + "\n")

