# -*- coding: utf-8 -*-
"""
上传更新到 192.168.5.60 服务器
"""

import paramiko
import os
import time

# 从环境变量读取服务器配置
HOST = os.environ.get('SSH_HOST', '192.168.5.60')
USER = os.environ.get('SSH_USER', 'ubains')
PASSWORD = os.environ.get('SSH_PASSWORD', '')
REMOTE_BASE = '/opt/troubleshoot'

if not PASSWORD:
    print("错误：SSH_PASSWORD 环境变量未设置")
    print("请设置环境变量或创建 .env 文件")
    exit(1)

# 本地路径
LOCAL_BASE = r'E:\github\ubains-module-test\develop\.claude\skills\Troubleshoot\code'

# 需要上传的文件
FILES_TO_UPLOAD = [
    ('web/server.py', 'web/server.py'),
    ('web/templates/index.html', 'web/templates/index.html'),
    ('requirements.txt', 'requirements.txt'),
]

def upload_files():
    """上传文件到服务器"""
    print("="*60)
    print("上传更新到服务器 192.168.5.60")
    print("="*60)

    # 连接 SSH
    print("\n[1/5] 连接 SSH...")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(HOST, username=USER, password=PASSWORD)
        print("OK: SSH 连接成功")

        # 备份原文件
        print("\n[2/5] 备份原文件...")
        timestamp = time.strftime('%Y%m%d_%H%M%S')
        stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_BASE} && cp web/server.py web/server.py.bak.{timestamp}')
        stdout.read()
        stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_BASE} && cp web/templates/index.html web/templates/index.html.bak.{timestamp}')
        stdout.read()
        print(f"OK: 已备份到 *.bak.{timestamp}")

        # 上传新文件
        print("\n[3/5] 上传新文件...")
        sftp = ssh.open_sftp()

        for local_rel, remote_rel in FILES_TO_UPLOAD:
            local_path = os.path.join(LOCAL_BASE, local_rel)
            remote_path = f"{REMOTE_BASE}/{remote_rel}"

            print(f"  上传: {local_rel}")
            try:
                sftp.put(local_path, remote_path)
                print(f"    OK: 已上传")
            except Exception as e:
                print(f"    错误: {e}")

        sftp.close()

        # 重启服务
        print("\n[4/5] 重启服务...")
        stdin, stdout, stderr = ssh.exec_command('pkill -f "python.*server.py"')
        stdout.read()
        time.sleep(1)

        stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_BASE}/web && nohup python server.py > /tmp/troubleshoot.log 2>&1 &')
        stdout.read()
        time.sleep(2)
        print("OK: 服务已重启")

        # 验证服务
        print("\n[5/5] 验证服务...")
        stdin, stdout, stderr = ssh.exec_command('curl -s http://localhost:8088/api/projects')
        result = stdout.read().decode()

        if '"success":true' in result:
            print("OK: 服务正常运行")
            print(f"    响应预览: {result[:100]}...")
        else:
            print("警告: 服务可能未正常启动")
            print(f"    响应: {result}")

        print("\n" + "="*60)
        print("更新完成！")
        print(f"访问地址: http://192.168.5.60:8088")
        print("="*60)

    except Exception as e:
        print(f"错误: {e}")
        return False
    finally:
        ssh.close()

    return True

if __name__ == '__main__':
    upload_files()