#!/usr/bin/env python3
"""
深度清理宝塔面板
"""
import requests
import time
import hashlib

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

BT_PANEL = "http://47.107.172.23:8888"
BT_API_KEY = "PKdfnaInQL0P5ghB8SvwbrGcIpXWaEvq"
DEPLOY_PATH = "/www/wwwroot/ai-interview"


def bt_api(action, data=None, timeout=60):
    if data is None:
        data = {}
    request_time = int(time.time())
    request_token = hashlib.md5(
        f"{request_time}{hashlib.md5(BT_API_KEY.encode()).hexdigest()}".encode()
    ).hexdigest()
    data['request_time'] = request_time
    data['request_token'] = request_token
    url = f"{BT_PANEL}/{action}"
    try:
        response = requests.post(url, data=data, timeout=timeout, verify=False)
        try:
            return response.json()
        except:
            return {"status": True, "msg": response.text[:2000]}
    except Exception as e:
        return {"status": False, "msg": str(e)}


def main():
    print("=" * 60)
    print("🧹 深度清理宝塔面板")
    print("=" * 60)
    
    # 1. 删除所有计划任务
    print("\n1. 清理计划任务...")
    result = bt_api("crontab?action=GetCrontab", {"page": 1, "limit": 100})
    
    deleted = 0
    tasks_to_delete = []
    
    if isinstance(result, list):
        tasks_to_delete = result
    elif isinstance(result, dict) and result.get("data"):
        tasks_to_delete = result["data"]
    
    for task in tasks_to_delete:
        if isinstance(task, dict) and task.get("id"):
            name = task.get("name", "")
            # 删除所有临时任务
            bt_api("crontab?action=DelCrontab", {"id": task["id"]})
            deleted += 1
            print(f"   删除: {name} (ID: {task['id']})")
    
    print(f"   共删除 {deleted} 个任务")
    
    # 2. 清理计划任务日志
    print("\n2. 清理任务日志...")
    result = bt_api("crontab?action=DelLogs")
    print(f"   结果: {result}")
    
    # 3. 清理面板日志
    print("\n3. 清理面板日志...")
    result = bt_api("system?action=ClearCache")
    print(f"   结果: {result}")
    
    # 4. 尝试压缩数据库
    print("\n4. 压缩数据库...")
    result = bt_api("system?action=ReDatabase")
    print(f"   结果: {result}")
    
    time.sleep(3)
    
    # 5. 再次尝试创建任务
    print("\n5. 测试创建任务...")
    result = bt_api("crontab?action=AddCrontab", {
        "name": "test_task",
        "type": "minute-n",
        "where1": "1",
        "sType": "toShell",
        "sBody": "echo test",
    })
    
    if result.get("status") and result.get("id"):
        print(f"   ✅ 成功! 任务ID: {result['id']}")
        # 删除测试任务
        bt_api("crontab?action=DelCrontab", {"id": result["id"]})
        
        # 现在执行构建
        print("\n6. 执行构建...")
        build_result = bt_api("crontab?action=AddCrontab", {
            "name": "deploy_docker",
            "type": "minute-n",
            "where1": "1",
            "sType": "toShell",
            "sBody": f"""#!/bin/bash
cd {DEPLOY_PATH}/deploy
docker system prune -af 2>/dev/null || true
docker-compose up -d --build 2>&1
sleep 15
docker ps -a
docker logs --tail 20 ai-interview-backend 2>&1
curl -s http://127.0.0.1:8000/health || echo "后端未响应"
""",
        })
        
        if build_result.get("id"):
            cron_id = build_result["id"]
            print(f"   任务 {cron_id} 已创建，开始执行...")
            bt_api("crontab?action=StartTask", {"id": cron_id}, timeout=600)
            print("   等待 180 秒...")
            time.sleep(180)
            
            log_result = bt_api("crontab?action=GetLogs", {"id": cron_id})
            bt_api("crontab?action=DelCrontab", {"id": cron_id})
            
            if log_result and log_result.get("msg"):
                print("\n📋 构建结果:")
                print("-" * 60)
                print(log_result["msg"])
    else:
        print(f"   ❌ 仍然失败: {result}")
    
    print("\n" + "=" * 60)
    print("🌐 http://interview.test.ai.ireborn.com.cn")


if __name__ == "__main__":
    main()
