#!/usr/bin/env python3
"""
启动 Docker 容器
"""
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 run_task(shell_body, task_name, wait_time=30):
    result = bt_api("crontab?action=AddCrontab", {
        "name": task_name,
        "type": "minute-n",
        "where1": "1",
        "sType": "toShell",
        "sBody": shell_body,
    })
    if not result.get("status") or not result.get("id"):
        print(f"创建任务失败: {result}")
        return None
    cron_id = result["id"]
    bt_api("crontab?action=StartTask", {"id": cron_id}, timeout=300)
    print(f"任务 {cron_id} 已启动，等待 {wait_time} 秒...")
    time.sleep(wait_time)
    log_result = bt_api("crontab?action=GetLogs", {"id": cron_id})
    bt_api("crontab?action=DelCrontab", {"id": cron_id})
    return log_result


def main():
    print("=" * 60)
    print("🚀 启动 Docker 容器")
    print("=" * 60)
    
    start_script = f"""#!/bin/bash
cd {DEPLOY_PATH}/deploy

echo "当前目录文件:"
ls -la

echo ""
echo "启动容器..."
docker-compose up -d 2>&1

sleep 10

echo ""
echo "========== 容器状态 =========="
docker ps -a --format 'table {{{{.Names}}}}\\t{{{{.Status}}}}\\t{{{{.Ports}}}}'

echo ""
echo "========== 后端日志 =========="
docker logs --tail 30 ai-interview-backend 2>&1

echo ""
echo "========== 测试服务 =========="
curl -s http://127.0.0.1:8000/health 2>&1 || echo "后端未响应"
echo ""
curl -s -o /dev/null -w "前端: HTTP %{{http_code}}" http://127.0.0.1:3000 2>&1
"""
    
    result = run_task(start_script, f"start_{int(time.time())}", wait_time=30)
    
    if result and result.get("msg"):
        print("\n" + result["msg"])
    
    print("\n" + "=" * 60)
    print("🌐 http://interview.test.ai.ireborn.com.cn")
    print("=" * 60)


if __name__ == "__main__":
    main()
