#!/usr/bin/env python3
"""
增强版 Gitea Webhook Ambassador 功能测试脚本
演示所有新增的监测和管理功能
"""

import asyncio
import aiohttp
import json
from datetime import datetime

BASE_URL = "http://localhost:8000"

async def test_health_check():
    """测试增强的健康检查"""
    print("🧪 测试增强的健康检查")
    print("-" * 50)
    
    async with aiohttp.ClientSession() as session:
        async with session.get(f"{BASE_URL}/health") as response:
            if response.status == 200:
                data = await response.json()
                print("✅ 健康检查通过")
                print(f"   状态: {data['status']}")
                print(f"   服务: {data['service']}")
                print(f"   Jenkins: {data['jenkins']['status']}")
                print(f"   工作池: {data['worker_pool']['active_workers']} 活跃工作线程")
                print(f"   队列大小: {data['worker_pool']['queue_size']}")
                print(f"   已处理: {data['worker_pool']['total_processed']}")
                print(f"   失败: {data['worker_pool']['total_failed']}")
            else:
                print(f"❌ 健康检查失败: {response.status}")
    
    print()

async def test_webhook():
    """测试 Webhook 功能"""
    print("🧪 测试 Webhook 功能")
    print("-" * 50)
    
    webhook_data = {
        "ref": "refs/heads/dev",
        "before": "abc123",
        "after": "def456",
        "repository": {
            "full_name": "freeleaps/test-project",
            "clone_url": "https://gitea.freeleaps.com/freeleaps/test-project.git"
        },
        "pusher": {
            "login": "developer",
            "email": "dev@freeleaps.com"
        }
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.post(
            f"{BASE_URL}/webhook/gitea",
            json=webhook_data
        ) as response:
            if response.status == 200:
                data = await response.json()
                print("✅ Webhook 处理成功")
                print(f"   响应: {data['message']}")
                print(f"   数据大小: {data['data']['body_size']} bytes")
            else:
                print(f"❌ Webhook 处理失败: {response.status}")
    
    print()

async def test_api_key_management():
    """测试 API 密钥管理"""
    print("🧪 测试 API 密钥管理")
    print("-" * 50)
    
    # 创建 API 密钥
    async with aiohttp.ClientSession() as session:
        # 创建密钥
        create_data = {"name": "test-api-key"}
        async with session.post(
            f"{BASE_URL}/api/admin/api-keys",
            json=create_data,
            headers={"Authorization": "Bearer test-token"}
        ) as response:
            if response.status == 200:
                data = await response.json()
                api_key = data['key']
                key_id = data['id']
                print(f"✅ API 密钥创建成功")
                print(f"   ID: {key_id}")
                print(f"   名称: {data['name']}")
                print(f"   密钥: {api_key[:8]}...{api_key[-8:]}")
                
                # 使用新创建的密钥测试日志端点
                print("\n   测试使用新密钥访问日志端点...")
                async with session.get(
                    f"{BASE_URL}/api/logs",
                    headers={"Authorization": f"Bearer {api_key}"}
                ) as log_response:
                    if log_response.status == 200:
                        logs = await log_response.json()
                        print(f"   ✅ 日志访问成功，获取到 {len(logs)} 条日志")
                    else:
                        print(f"   ❌ 日志访问失败: {log_response.status}")
                
                # 删除密钥
                async with session.delete(
                    f"{BASE_URL}/api/admin/api-keys/{key_id}",
                    headers={"Authorization": f"Bearer {api_key}"}
                ) as delete_response:
                    if delete_response.status == 200:
                        print(f"   ✅ API 密钥删除成功")
                    else:
                        print(f"   ❌ API 密钥删除失败: {delete_response.status}")
            else:
                print(f"❌ API 密钥创建失败: {response.status}")
    
    print()

async def test_project_mapping():
    """测试项目映射管理"""
    print("🧪 测试项目映射管理")
    print("-" * 50)
    
    mapping_data = {
        "repository_name": "freeleaps/test-project",
        "default_job": "test-project-build",
        "branch_jobs": [
            {"branch": "dev", "job": "test-project-dev"},
            {"branch": "staging", "job": "test-project-staging"}
        ],
        "branch_patterns": [
            {"pattern": "feature/*", "job": "test-project-feature"},
            {"pattern": "hotfix/*", "job": "test-project-hotfix"}
        ]
    }
    
    async with aiohttp.ClientSession() as session:
        # 创建项目映射
        async with session.post(
            f"{BASE_URL}/api/admin/projects",
            json=mapping_data,
            headers={"Authorization": "Bearer test-token"}
        ) as response:
            if response.status == 200:
                data = await response.json()
                print("✅ 项目映射创建成功")
                print(f"   ID: {data['id']}")
                print(f"   仓库: {data['repository_name']}")
                print(f"   默认任务: {data['default_job']}")
                print(f"   分支任务数: {len(data['branch_jobs'])}")
                print(f"   分支模式数: {len(data['branch_patterns'])}")
            else:
                print(f"❌ 项目映射创建失败: {response.status}")
    
    print()

async def test_logs_and_stats():
    """测试日志和统计功能"""
    print("🧪 测试日志和统计功能")
    print("-" * 50)
    
    async with aiohttp.ClientSession() as session:
        # 获取日志统计
        async with session.get(
            f"{BASE_URL}/api/logs/stats",
            headers={"Authorization": "Bearer test-token"}
        ) as response:
            if response.status == 200:
                stats = await response.json()
                print("✅ 日志统计获取成功")
                print(f"   总日志数: {stats['total_logs']}")
                print(f"   成功日志: {stats['successful_logs']}")
                print(f"   失败日志: {stats['failed_logs']}")
                print(f"   最近24小时: {stats['recent_logs_24h']}")
                print(f"   仓库统计: {len(stats['repository_stats'])} 个仓库")
            else:
                print(f"❌ 日志统计获取失败: {response.status}")
    
    print()

async def test_admin_stats():
    """测试管理统计"""
    print("🧪 测试管理统计")
    print("-" * 50)
    
    async with aiohttp.ClientSession() as session:
        async with session.get(
            f"{BASE_URL}/api/admin/stats",
            headers={"Authorization": "Bearer test-token"}
        ) as response:
            if response.status == 200:
                stats = await response.json()
                print("✅ 管理统计获取成功")
                print(f"   API 密钥总数: {stats['api_keys']['total']}")
                print(f"   活跃密钥: {stats['api_keys']['active']}")
                print(f"   最近使用: {stats['api_keys']['recently_used']}")
                print(f"   项目映射总数: {stats['project_mappings']['total']}")
            else:
                print(f"❌ 管理统计获取失败: {response.status}")
    
    print()

async def main():
    """主测试函数"""
    print("🚀 开始增强版 Gitea Webhook Ambassador 功能测试")
    print("=" * 60)
    print()
    
    try:
        await test_health_check()
        await test_webhook()
        await test_api_key_management()
        await test_project_mapping()
        await test_logs_and_stats()
        await test_admin_stats()
        
        print("=" * 60)
        print("🎉 所有测试完成！")
        print("✅ Python 版本现在具备了与 Go 版本相同的监测和管理功能")
        
    except Exception as e:
        print(f"❌ 测试过程中出现错误: {str(e)}")

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