#!/usr/bin/env python3
"""sync_dashboard.py — 数据同步包装脚本
1. 运行 update_data.py
2. 检查 server 是否正常
3. server 挂了就重启
"""
import subprocess
import sys
import os

DASHBOARD_DIR = "/home/hmo/web-dashboard"
SERVER_PORT = 8899

def run_update():
    """运行 update_data.py，返回 stdout"""
    try:
        r = subprocess.run(
            ["python3", "update_data.py"],
            cwd=DASHBOARD_DIR,
            capture_output=True, text=True, timeout=60,
        )
        return r.stdout.strip() if r.returncode == 0 else None
    except Exception as e:
        print(f"❌ update_data.py 执行失败: {e}", file=sys.stderr)
        return None

def check_server():
    """检查 server 是否正常"""
    import urllib.request
    try:
        req = urllib.request.Request(f"http://localhost:{SERVER_PORT}", 
                                      headers={"User-Agent": "Mozilla/5.0"})
        with urllib.request.urlopen(req, timeout=5) as r:
            return r.status == 200
    except:
        return False

def restart_server():
    """重启 server"""
    try:
        subprocess.run(
            ["python3", "server.py", str(SERVER_PORT)],
            cwd=DASHBOARD_DIR,
            capture_output=True, timeout=10,
        )
        return True
    except Exception as e:
        print(f"❌ server 重启失败: {e}", file=sys.stderr)
        return False

def main():
    output = run_update()
    server_ok = check_server()

    if output:
        # update_data.py 有输出 → 转发
        print(output)
        if not server_ok:
            print("⚠️ 注意：server 似乎未响应，但数据已更新")
    else:
        if server_ok:
            # 无输出 + server 正常 → SILENT
            print("[SILENT] 数据无更新，server运行正常")
        else:
            # server 挂了 → 重启
            print("⚠️ server 无响应，尝试重启...")
            if restart_server():
                print("✅ server 已重启")
                # 再检查一次
                if check_server():
                    print("✅ server 恢复运行")
                else:
                    print("❌ server 仍未响应，需人工检查")
            else:
                print("❌ server 重启失败")

if __name__ == "__main__":
    main()
