#!/usr/bin/env python3
"""
部署脚本 - 更新服务器 192.168.5.60 的前端和后端代码
"""
import paramiko
import sys
import time

def deploy(restart_backend=True, restart_frontend=True):
    host = "192.168.5.60"
    username = "ubains"
    password = "Ubains@123"
    deploy_dir = "/data/third_party/plat-auto-test"

    commands = [
        # 拉取最新代码
        f"cd {deploy_dir} && git pull origin platform-auto-test",
    ]

    if restart_backend:
        commands.extend([
            # 重启后端容器（应用 Python 代码变更）
            "docker compose -f /data/third_party/plat-auto-test/deploy/docker-compose.yml restart app",
            "sleep 5",  # 等待容器启动
            "docker compose -f /data/third_party/plat-auto-test/deploy/docker-compose.yml ps app",
        ])

    if restart_frontend:
        commands.extend([
            # 重启前端容器（如果前端有变更）
            "docker compose -f /data/third_party/plat-auto-test/deploy/docker-compose.yml restart nginx",
        ])

    print(f"连接服务器 {host}...")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(host, username=username, password=password, timeout=30)
        print("连接成功")

        for cmd in commands:
            print(f"\n执行: {cmd}")
            stdin, stdout, stderr = ssh.exec_command(cmd, timeout=120)
            out = stdout.read().decode('utf-8')
            err = stderr.read().decode('utf-8')
            if out:
                print(out)
            if err and "warning" not in err.lower():
                print(f"[stderr] {err}")

        print("\n" + "=" * 50)
        print("部署完成!")
        print("=" * 50)
        print("访问地址:")
        print("  前端: http://192.168.5.60")
        print("  API 文档: http://192.168.5.60/docs")
        print("  健康检查: http://192.168.5.60/health")

    except Exception as e:
        print(f"错误: {e}")
        sys.exit(1)
    finally:
        ssh.close()

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="部署到 192.168.5.60")
    parser.add_argument("--backend-only", action="store_true", help="只重启后端")
    parser.add_argument("--frontend-only", action="store_true", help="只重启前端")
    parser.add_argument("--no-restart", action="store_true", help="只拉取代码，不重启容器")
    args = parser.parse_args()

    if args.no_restart:
        deploy(restart_backend=False, restart_frontend=False)
    elif args.backend_only:
        deploy(restart_backend=True, restart_frontend=False)
    elif args.frontend_only:
        deploy(restart_backend=False, restart_frontend=True)
    else:
        deploy()