#!/usr/bin/env python3
"""
通过文件 API 写入部署脚本
"""
import requests
import time
import hashlib
import base64

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 main():
    print("=" * 60)
    print("📝 写入部署脚本到服务器")
    print("=" * 60)
    
    deploy_script = f"""#!/bin/bash
# AI Interview 部署脚本

cd {DEPLOY_PATH}/deploy

echo "清理 Docker..."
docker system prune -af 2>/dev/null || true

echo "构建并启动..."
docker-compose up -d --build

sleep 15

echo "容器状态:"
docker ps -a

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

echo "测试:"
curl -s http://127.0.0.1:8000/health || echo "后端未响应"
"""
    
    # 方法1: 尝试写入已存在的路径
    paths_to_try = [
        f"{DEPLOY_PATH}/deploy.sh",
        f"{DEPLOY_PATH}/deploy/deploy.sh",
        "/tmp/deploy.sh",
    ]
    
    for path in paths_to_try:
        print(f"\n尝试写入: {path}")
        
        # 先尝试创建空文件
        result = bt_api("files?action=CreateFile", {"path": path})
        print(f"   创建文件: {result}")
        
        # 然后写入内容
        result = bt_api("files?action=SaveFileBody", {
            "path": path,
            "data": deploy_script,
            "encoding": "utf-8"
        })
        
        if result.get("status"):
            print(f"   ✅ 写入成功!")
            print()
            print("=" * 60)
            print("请在服务器执行:")
            print(f"   bash {path}")
            print("=" * 60)
            return
        else:
            print(f"   ❌ {result.get('msg', result)}")
    
    print()
    print("=" * 60)
    print("❌ 所有方法都失败了")
    print()
    print("请手动在服务器终端执行:")
    print()
    print(f"cd {DEPLOY_PATH}/deploy")
    print("docker system prune -af")
    print("docker-compose up -d --build")
    print("=" * 60)


if __name__ == "__main__":
    main()
