#!/usr/bin/env python3
"""
检查 Docker 容器状态
"""
import requests
import time
import hashlib

# 禁用 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[:2000]}
    except Exception as e:
        return {"status": False, "msg": str(e)}


def run_and_get_log(shell_body, task_name):
    """创建计划任务，运行并获取日志"""
    # 1. 创建任务
    result = bt_api("crontab?action=AddCrontab", {
        "name": task_name,
        "type": "minute-n",
        "where1": "1",
        "hour": "",
        "minute": "",
        "week": "",
        "sType": "toShell",
        "sBody": shell_body,
        "sName": "",
        "backupTo": "",
        "save": "",
        "urladdress": ""
    })
    
    if not result.get("status") or not result.get("id"):
        print(f"创建任务失败: {result}")
        return None
    
    cron_id = result["id"]
    print(f"任务创建成功，ID: {cron_id}")
    
    # 2. 执行任务
    bt_api("crontab?action=StartTask", {"id": cron_id}, timeout=120)
    print("任务已启动，等待执行...")
    time.sleep(10)
    
    # 3. 获取日志
    log_result = bt_api("crontab?action=GetLogs", {"id": cron_id})
    
    # 4. 删除任务
    bt_api("crontab?action=DelCrontab", {"id": cron_id})
    
    return log_result


def main():
    print("=" * 60)
    print("🔍 检查 Docker 容器状态")
    print("=" * 60)
    print()
    
    # 检查命令
    check_script = f"""#!/bin/bash
echo "========== Docker 容器状态 =========="
docker ps -a
echo ""
echo "========== Docker Compose 状态 =========="
cd {DEPLOY_PATH}/deploy && docker-compose ps 2>&1 || echo "docker-compose 未运行"
echo ""
echo "========== 后端容器日志 (最后 50 行) =========="
docker logs --tail 50 ai-interview-backend 2>&1 || echo "后端容器不存在"
echo ""
echo "========== 检查端口 =========="
netstat -tlnp | grep -E ':(3000|8000)' || ss -tlnp | grep -E ':(3000|8000)' || echo "端口未监听"
echo ""
echo "========== 测试本地服务 =========="
curl -s http://127.0.0.1:8000/health 2>&1 || echo "后端 8000 端口无响应"
curl -s -o /dev/null -w "前端 3000 端口: HTTP %{{http_code}}" http://127.0.0.1:3000 2>&1 || echo "前端 3000 端口无响应"
"""
    
    result = run_and_get_log(check_script, f"check_docker_{int(time.time())}")
    
    if result:
        print("\n📋 执行结果:")
        print("-" * 60)
        if isinstance(result, dict) and result.get("msg"):
            print(result["msg"])
        else:
            print(result)
    
    print()
    print("=" * 60)


if __name__ == "__main__":
    main()
