#!/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 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("🚀 单独启动后端容器")
    print("=" * 60)
    
    # 直接用 docker run 启动后端容器
    start_script = f"""#!/bin/bash
cd {DEPLOY_PATH}/deploy

# 停止旧容器
docker stop ai-interview-backend 2>/dev/null || true
docker rm ai-interview-backend 2>/dev/null || true

# 读取 .env 文件
source .env 2>/dev/null || true

echo "启动后端容器..."
docker run -d \\
    --name ai-interview-backend \\
    -p 8000:8000 \\
    -e COZE_PAT_TOKEN="$COZE_PAT_TOKEN" \\
    -e COZE_BOT_ID="$COZE_BOT_ID" \\
    -e COZE_WORKFLOW_A_ID="$COZE_WORKFLOW_A_ID" \\
    -e COZE_WORKFLOW_C_ID="$COZE_WORKFLOW_C_ID" \\
    -e FILE_SERVER_URL="$FILE_SERVER_URL" \\
    -e FILE_SERVER_TOKEN="$FILE_SERVER_TOKEN" \\
    -v {DEPLOY_PATH}/deploy/uploads:/app/uploads \\
    --restart unless-stopped \\
    deploy-backend

sleep 5

echo ""
echo "========== 容器状态 =========="
docker ps --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 "后端未响应"
"""
    
    result = run_task(start_script, f"start_backend_{int(time.time())}", wait_time=20)
    
    if result and result.get("msg"):
        print("\n" + result["msg"])
    
    print("\n" + "=" * 60)
    print("测试后端 API:")
    print("  http://interview.test.ai.ireborn.com.cn/api/health")
    print("=" * 60)


if __name__ == "__main__":
    main()
