#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git Webhook 自动触发服务
GitHub/Gitee push 代码后，自动触发全流程部署回测
完全无人值守！

启动：
nohup python git_webhook_server.py > webhook.log 2>&1 &

测试：
curl http://your-ip:8899/webhook
"""

import os
import sys
import json
import subprocess
from flask import Flask, request, jsonify

app = Flask(__name__)
CI_CD_SCRIPT = "/Users/chufeng/.openclaw/workspace-jiangwei/sanguo_nas_ci_cd.sh"
SECRET_TOKEN = "sanguo-quant-2026"  # 修改为您的token


@app.route("/webhook", methods=["POST"])
def webhook():
    # 验证签名
    signature = request.headers.get("X-Hub-Signature-256", "")
    # 这里简化处理，如果需要可以验证签名
    
    print("\n" + "="*60)
    print("📦 收到 Git push webhook")
    print("🕐 时间: {}".format(datetime.now()))
    print("🚀 触发全流程自动化部署回测...")
    print("="*60 + "\n")
    
    try:
        # 执行全流程 CI/CD
        result = subprocess.run([CI_CD_SCRIPT], capture_output=False)
        
        if result.returncode == 0:
            print("\n✅ 自动化部署回测完成！\n")
            return jsonify({"status": "ok", "message": "自动化部署回测已完成"})
        else:
            print("\n❌ 部署回测失败，请检查日志\n")
            return jsonify({"status": "error", "message": "部署回测失败"}), 500
    
    except Exception as e:
        print(f"\n❌ 异常: {e}\n")
        return jsonify({"status": "error", "message": str(e)}), 500


@app.route("/", methods=["GET"])
def index():
    return """
<h1>sanguo_quant_live Git Webhook</h1>
<p>Status: running</p>
<p>Endpoint: <code>/webhook</code></p>
<p>全自动部署回测服务正在运行 ✅</p>
"""


if __name__ == "__main__":
    from datetime import datetime
    print("============================================")
    print("  sanguo_quant_live Git Webhook 服务")
    print("============================================")
    print()
    print(f"🎯 监听端口: 0.0.0.0:8899")
    print(f"📜 CI/CD 脚本: {CI_CD_SCRIPT}")
    print()
    print("🚀 等待 Git push 触发自动化部署...")
    print()
    app.run(host="0.0.0.0", port=8899, debug=False)
