#!/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=GetCrontab", {"page": 1, "limit": 100})
    if isinstance(result, dict) and result.get("data"):
        for task in result["data"]:
            if isinstance(task, dict) and ("upload_" in task.get("name", "") or "build_" in task.get("name", "")):
                bt_api("crontab?action=DelCrontab", {"id": task["id"]})
    
    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=600)
    print(f"任务 {cron_id} 启动，等待 {wait_time}s...")
    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)
    
    # 先清理磁盘空间
    print("\n🧹 步骤 1: 清理磁盘空间...")
    cleanup_script = """#!/bin/bash
echo "清理 Docker..."
docker system prune -af --volumes 2>/dev/null || true
docker builder prune -af 2>/dev/null || true

echo ""
echo "清理宝塔日志..."
rm -rf /www/wwwlogs/*.log 2>/dev/null || true
find /www/server/panel/logs -name "*.log" -mtime +1 -delete 2>/dev/null || true

echo ""
echo "磁盘使用:"
df -h /
"""
    result = run_task(cleanup_script, "cleanup", wait_time=30)
    if result and result.get("msg"):
        print(result["msg"][:1000])
    
    # 构建
    print("\n🐳 步骤 2: 构建并启动...")
    build_script = f"""#!/bin/bash
cd {DEPLOY_PATH}/deploy

echo "目录检查:"
ls -la {DEPLOY_PATH}/frontend/ | head -5
ls -la {DEPLOY_PATH}/backend/ | head -5

echo ""
echo "构建并启动..."
docker-compose up -d --build 2>&1

sleep 20

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_code}}" http://127.0.0.1:3000 2>&1
"""
    
    result = run_task(build_script, "build", wait_time=180)
    
    if result and result.get("msg"):
        print("\n📋 构建结果:")
        print("-" * 60)
        print(result["msg"])
    
    print("\n" + "=" * 60)
    print("🌐 http://interview.test.ai.ireborn.com.cn")
    print("=" * 60)


if __name__ == "__main__":
    main()
