#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
部署智能定位功能到 192.168.5.60 服务器
"""
import paramiko
import os
import sys

# 服务器配置
SERVER = "192.168.5.60"
USER = "ubains"
PASSWORD = "Ubains@123"
DEPLOY_DIR = "/data/third_party/plat-auto-test"

# 需要上传的文件列表
FILES_TO_UPLOAD = [
    # 新增文件
    ("backend/app/models/login_template.py", "backend/app/models/login_template.py"),
    ("backend/app/routers/login_template.py", "backend/app/routers/login_template.py"),
    ("backend/app/routers/smart_locate.py", "backend/app/routers/smart_locate.py"),
    ("backend/app/schemas/login_template.py", "backend/app/schemas/login_template.py"),
    ("backend/app/services/keyword_matcher.py", "backend/app/services/keyword_matcher.py"),
    ("backend/app/services/login_template_service.py", "backend/app/services/login_template_service.py"),
    ("backend/app/services/selector_extractor.py", "backend/app/services/selector_extractor.py"),
    ("backend/app/services/smart_locate_service.py", "backend/app/services/smart_locate_service.py"),
    # 修改的文件
    ("backend/app/main.py", "backend/app/main.py"),
    ("backend/app/models/__init__.py", "backend/app/models/__init__.py"),
    ("frontend/src/api/elementLocate.ts", "frontend/src/api/elementLocate.ts"),
    ("frontend/src/views/Cases.vue", "frontend/src/views/Cases.vue"),
]

def deploy():
    """部署到服务器"""
    print("=" * 60)
    print("部署智能定位功能到服务器")
    print("=" * 60)
    print(f"服务器: {SERVER}")
    print(f"用户: {USER}")
    print(f"部署目录: {DEPLOY_DIR}")
    print()

    # 连接服务器
    print("连接服务器...")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(SERVER, username=USER, password=PASSWORD)
        print("[OK] SSH 连接成功")
    except Exception as e:
        print(f"[FAIL] SSH 连接失败: {e}")
        return False

    sftp = ssh.open_sftp()

    # 上传文件
    print(f"\n上传 {len(FILES_TO_UPLOAD)} 个文件...")

    local_base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    success_count = 0
    for local_path, remote_path in FILES_TO_UPLOAD:
        full_local = os.path.join(local_base, local_path)
        full_remote = f"{DEPLOY_DIR}/{remote_path}"

        try:
            # 确保远程目录存在
            remote_dir = os.path.dirname(full_remote)
            try:
                sftp.stat(remote_dir)
            except FileNotFoundError:
                ssh.exec_command(f"mkdir -p {remote_dir}")

            # 上传文件
            sftp.put(full_local, full_remote)
            print(f"  [OK] {remote_path}")
            success_count += 1
        except Exception as e:
            print(f"  [FAIL] {remote_path}: {e}")

    sftp.close()

    print(f"\n上传完成: {success_count}/{len(FILES_TO_UPLOAD)} 成功")

    # 重启容器
    print("\n重启 Docker 容器...")
    stdin, stdout, stderr = ssh.exec_command(f"cd {DEPLOY_DIR}/deploy && docker compose restart app")
    print(stdout.read().decode())
    print(stderr.read().decode())

    # 等待服务启动
    print("等待服务启动...")
    import time
    time.sleep(5)

    # 验证部署
    print("\n验证部署...")
    stdin, stdout, stderr = ssh.exec_command("curl -s http://localhost:8001/api/element/health")
    result = stdout.read().decode()
    if "smart-locate" in result or "healthy" in result:
        print("[OK] 智能定位 API 已部署")
    else:
        print(f"[WARN] 验证结果: {result}")

    stdin, stdout, stderr = ssh.exec_command("curl -s http://localhost:8001/api/login-templates")
    result = stdout.read().decode()
    if "template" in result:
        print("[OK] 登录模板 API 已部署")
    else:
        print(f"[WARN] 验证结果: {result[:200]}")

    ssh.close()
    print("\n部署完成!")
    return True


if __name__ == "__main__":
    deploy()