#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据清理功能测试脚本

测试清理服务的各个功能。
"""

import asyncio
import httpx
import json
from datetime import datetime

API_BASE = "http://localhost:8001"


async def test_cleanup():
    """测试清理功能"""
    async with httpx.AsyncClient(timeout=30.0) as client:
        print("=" * 60)
        print("Cleanup Service Test")
        print("=" * 60)

        # 1. 获取存储统计
        print("\n[Step 1] Getting storage stats...")
        response = await client.get(f"{API_BASE}/api/cleanup/stats")
        stats = response.json()["data"]

        print(f"  Screenshots: {stats['screenshots']['count']} files, {stats['screenshots']['size']/1024/1024:.2f} MB")
        print(f"  Reports: {stats['reports']['count']} files, {stats['reports']['size']/1024/1024:.2f} MB")
        print(f"  Database: {stats['database']['size']/1024:.1f} KB")
        print(f"  Executions: {stats['database']['executions']}")
        print(f"  Case Results: {stats['database']['case_results']}")

        # 2. 模拟清理
        print("\n[Step 2] Testing dry run cleanup (days=7)...")
        response = await client.post(
            f"{API_BASE}/api/cleanup/cleanup",
            params={"days": 7, "dry_run": True}
        )
        result = response.json()
        print(f"  Success: {result['success']}")
        print(f"  Message: {result['message']}")
        print(f"  Data: {json.dumps(result['data'], indent=2)}")

        # 3. 模拟清理孤儿截图
        print("\n[Step 3] Testing orphan screenshots cleanup (dry run)...")
        response = await client.post(
            f"{API_BASE}/api/cleanup/cleanup/orphan-screenshots",
            params={"dry_run": True}
        )
        result = response.json()
        print(f"  Success: {result['success']}")
        print(f"  Message: {result['message']}")
        print(f"  Orphan screenshots: {result['data']['count']}")

        # 4. 实际清理（保留30天）
        print("\n[Step 4] Performing actual cleanup (days=30)...")
        response = await client.post(
            f"{API_BASE}/api/cleanup/cleanup",
            params={"days": 30, "dry_run": False}
        )
        result = response.json()
        print(f"  Success: {result['success']}")
        print(f"  Message: {result['message']}")
        print(f"  Screenshots deleted: {result['data']['screenshots']}")
        print(f"  Reports deleted: {result['data']['reports']}")
        print(f"  Executions deleted: {result['data']['executions']}")
        print(f"  Space freed: {result['data']['freed_space']/1024/1024:.2f} MB")

        # 5. 获取清理后的统计
        print("\n[Step 5] Getting stats after cleanup...")
        response = await client.get(f"{API_BASE}/api/cleanup/stats")
        stats_after = response.json()["data"]

        print(f"  Screenshots: {stats_after['screenshots']['count']} files, {stats_after['screenshots']['size']/1024/1024:.2f} MB")
        print(f"  Reports: {stats_after['reports']['count']} files, {stats_after['reports']['size']/1024/1024:.2f} MB")
        print(f"  Executions: {stats_after['database']['executions']}")
        print(f"  Case Results: {stats_after['database']['case_results']}")

        print("\n" + "=" * 60)
        print("Test completed!")
        print("=" * 60)


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