"""
团队看板API测试脚本

用于验证团队看板所有接口的功能
"""

import asyncio
import httpx

# 配置
BASE_URL = "http://localhost:8000"
# 需要先登录获取token
TOKEN = "your_token_here"  # 替换为实际的token

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type": "application/json"
}


async def test_overview():
    """测试团队概览接口"""
    print("\n=== 测试团队概览接口 ===")
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_URL}/api/v1/team/dashboard/overview",
            headers=headers
        )
        print(f"状态码: {response.status_code}")
        data = response.json()
        print(f"响应数据: {data}")
        
        if data.get("code") == 200:
            result = data.get("data", {})
            print(f"✅ 团队成员数: {result.get('member_count')}")
            print(f"✅ 平均学习进度: {result.get('avg_progress')}%")
            print(f"✅ 平均考试成绩: {result.get('avg_score')}")
            print(f"✅ 课程完成率: {result.get('course_completion_rate')}%")
        else:
            print(f"❌ 失败: {data.get('message')}")


async def test_progress():
    """测试学习进度接口"""
    print("\n=== 测试学习进度接口 ===")
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_URL}/api/v1/team/dashboard/progress",
            headers=headers
        )
        print(f"状态码: {response.status_code}")
        data = response.json()
        
        if data.get("code") == 200:
            result = data.get("data", {})
            print(f"✅ 成员列表: {result.get('members')}")
            print(f"✅ 周数: {len(result.get('weeks', []))}")
            print(f"✅ 数据条数: {len(result.get('data', []))}")
        else:
            print(f"❌ 失败: {data.get('message')}")


async def test_course_distribution():
    """测试课程分布接口"""
    print("\n=== 测试课程分布接口 ===")
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_URL}/api/v1/team/dashboard/course-distribution",
            headers=headers
        )
        print(f"状态码: {response.status_code}")
        data = response.json()
        
        if data.get("code") == 200:
            result = data.get("data", {})
            print(f"✅ 已完成: {result.get('completed')}")
            print(f"✅ 进行中: {result.get('in_progress')}")
            print(f"✅ 未开始: {result.get('not_started')}")
        else:
            print(f"❌ 失败: {data.get('message')}")


async def test_ability_analysis():
    """测试能力分析接口"""
    print("\n=== 测试能力分析接口 ===")
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_URL}/api/v1/team/dashboard/ability-analysis",
            headers=headers
        )
        print(f"状态码: {response.status_code}")
        data = response.json()
        
        if data.get("code") == 200:
            result = data.get("data", {})
            radar = result.get('radar_data', {})
            print(f"✅ 能力维度: {radar.get('dimensions')}")
            print(f"✅ 能力分数: {radar.get('values')}")
            print(f"✅ 短板数量: {len(result.get('weaknesses', []))}")
        else:
            print(f"❌ 失败: {data.get('message')}")


async def test_rankings():
    """测试排行榜接口"""
    print("\n=== 测试排行榜接口 ===")
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_URL}/api/v1/team/dashboard/rankings",
            headers=headers
        )
        print(f"状态码: {response.status_code}")
        data = response.json()
        
        if data.get("code") == 200:
            result = data.get("data", {})
            study_ranking = result.get('study_time_ranking', [])
            score_ranking = result.get('score_ranking', [])
            print(f"✅ 学习时长排行: {len(study_ranking)} 人")
            if study_ranking:
                print(f"   第一名: {study_ranking[0].get('name')} - {study_ranking[0].get('study_time')}小时")
            print(f"✅ 成绩排行: {len(score_ranking)} 人")
            if score_ranking:
                print(f"   第一名: {score_ranking[0].get('name')} - {score_ranking[0].get('avg_score')}分")
        else:
            print(f"❌ 失败: {data.get('message')}")


async def test_activities():
    """测试团队动态接口"""
    print("\n=== 测试团队动态接口 ===")
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"{BASE_URL}/api/v1/team/dashboard/activities",
            headers=headers
        )
        print(f"状态码: {response.status_code}")
        data = response.json()
        
        if data.get("code") == 200:
            result = data.get("data", {})
            activities = result.get('activities', [])
            print(f"✅ 活动记录数: {len(activities)}")
            if activities:
                print(f"   最新活动: {activities[0].get('user_name')} {activities[0].get('action')} {activities[0].get('target')}")
        else:
            print(f"❌ 失败: {data.get('message')}")


async def main():
    """运行所有测试"""
    print("=" * 60)
    print("团队看板API测试")
    print("=" * 60)
    
    # 检查token是否设置
    if TOKEN == "your_token_here":
        print("\n⚠️  请先设置TOKEN变量（在文件顶部）")
        print("   可以通过以下步骤获取：")
        print("   1. 访问 http://localhost:3001")
        print("   2. 登录系统（admin账号）")
        print("   3. 打开浏览器开发者工具 -> Application -> Local Storage")
        print("   4. 找到 token 或 access_token")
        return
    
    try:
        await test_overview()
        await test_progress()
        await test_course_distribution()
        await test_ability_analysis()
        await test_rankings()
        await test_activities()
        
        print("\n" + "=" * 60)
        print("✅ 所有测试完成！")
        print("=" * 60)
        
    except Exception as e:
        print(f"\n❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()


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

