#!/usr/bin/env python3
"""
通过宝塔计划任务重启 Docker 容器
"""
import requests
import time
import hashlib
import json

# 禁用 SSL 警告
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):
    """调用宝塔 API"""
    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[:500]}
    except Exception as e:
        return {"status": False, "msg": str(e)}


def add_crontab(name, shell_body):
    """添加计划任务"""
    print(f"📋 添加计划任务: {name}")
    result = bt_api("crontab?action=AddCrontab", {
        "name": name,
        "type": "minute-n",
        "where1": "1",
        "hour": "",
        "minute": "",
        "week": "",
        "sType": "toShell",
        "sBody": shell_body,
        "sName": "",
        "backupTo": "",
        "save": "",
        "urladdress": ""
    })
    print(f"   结果: {result}")
    return result


def exec_crontab(cron_id):
    """立即执行计划任务"""
    print(f"▶️ 执行计划任务 ID: {cron_id}")
    result = bt_api("crontab?action=StartTask", {"id": cron_id}, timeout=300)
    print(f"   结果: {result}")
    return result


def delete_crontab(cron_id):
    """删除计划任务"""
    print(f"🗑️ 删除计划任务 ID: {cron_id}")
    result = bt_api("crontab?action=DelCrontab", {"id": cron_id})
    print(f"   结果: {result}")
    return result


def get_crontab_list():
    """获取计划任务列表"""
    result = bt_api("crontab?action=GetCrontab", {"page": 1, "search": ""})
    return result


def main():
    print("=" * 60)
    print("🐳 重启 Docker 容器")
    print("=" * 60)
    print()
    
    # Docker 重启命令
    shell_body = f"""#!/bin/bash
cd {DEPLOY_PATH}/deploy
docker-compose down 2>/dev/null || true
sleep 2
docker-compose up -d --build
sleep 5
echo "Docker 容器状态:"
docker ps --format 'table {{{{.Names}}}}\\t{{{{.Status}}}}\\t{{{{.Ports}}}}'
echo ""
echo "测试后端服务:"
curl -s http://127.0.0.1:8000/health || echo "后端未响应"
echo ""
echo "测试前端服务:"
curl -s -o /dev/null -w "HTTP Status: %{{http_code}}" http://127.0.0.1:3000 || echo "前端未响应"
"""
    
    # 1. 添加计划任务
    task_name = f"restart_docker_{int(time.time())}"
    result = add_crontab(task_name, shell_body)
    
    if result.get("status") and result.get("id"):
        cron_id = result["id"]
        print(f"\n✅ 计划任务创建成功，ID: {cron_id}")
        
        # 2. 立即执行
        print("\n🚀 立即执行计划任务...")
        exec_result = exec_crontab(cron_id)
        
        # 3. 等待执行完成
        print("\n⏳ 等待执行完成...")
        time.sleep(30)
        
        # 4. 删除计划任务
        delete_crontab(cron_id)
        
        print("\n✅ Docker 重启命令已执行!")
    else:
        print(f"\n❌ 计划任务创建失败: {result}")
        print("\n⚠️ 请手动在服务器执行:")
        print(f"   cd {DEPLOY_PATH}/deploy")
        print("   docker-compose down && docker-compose up -d --build")
    
    print()
    print("=" * 60)
    print("🌐 访问地址:")
    print("   http://interview.test.ai.ireborn.com.cn")
    print("   http://interview.test.ai.ireborn.com.cn/admin")
    print("=" * 60)


if __name__ == "__main__":
    main()
