# -*- coding: utf-8 -*-
"""
upload_to_server.py - 上传更新的文件到 192.168.5.60 服务器
"""

import paramiko
import os
import time
from datetime import datetime

# 配置
HOST = '192.168.5.60'
USER = 'ubains'
PASSWORD = 'Ubains@123'
REMOTE_BASE = '/opt/troubleshoot'

# 本地部署目录
LOCAL_BASE = os.path.dirname(os.path.abspath(__file__))

# 需要上传的文件
FILES_TO_UPLOAD = [
    ('web/server.py', 'web/server.py'),
    ('web/safety_filter.py', 'web/safety_filter.py'),
    ('web/cache_manager.py', 'web/cache_manager.py'),
]

def upload_files():
    print("="*60)
    print("  Troubleshoot - Upload Files")
    print("="*60)
    print("Server: " + HOST)
    print("User: " + USER)
    print("Remote: " + REMOTE_BASE)
    print("="*60)

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        print("\n[1/4] Connecting...")
        ssh.connect(HOST, username=USER, password=PASSWORD)
        print("[OK] Connected")

        print("\n[2/4] Backing up...")
        today = datetime.now().strftime('%Y%m%d')

        print("\n[3/4] Uploading files...")
        sftp = ssh.open_sftp()

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

            if os.path.exists(local_path):
                print("  Uploading: " + local_rel)
                sftp.put(local_path, remote_path)
                print("  [OK] " + remote_path)
            else:
                print("  [FAIL] File not found: " + local_path)

        sftp.close()
        print("\n[OK] Files uploaded")

        print("\n[4/4] Restarting service...")
        restart_cmd = (
            'cd /opt/troubleshoot/web && '
            'pkill -f "python.*server.py" || true && '
            'sleep 2 && '
            'nohup python3 server.py > /tmp/troubleshoot.log 2>&1 &'
        )
        stdin, stdout, stderr = ssh.exec_command(restart_cmd)
        stdout.read()
        print("[OK] Service restarted")

        print("\nWaiting for service...")
        time.sleep(3)

        print("\n[5/5] Verifying...")
        stdin, stdout, stderr = ssh.exec_command('curl -s http://localhost:8088/api/health')
        result = stdout.read().decode()

        if result and 'ok' in result:
            print("[OK] Service is running")
            print("\nHealth check response:")
            print(result[:300])
        else:
            print("[FAIL] Service may not be running")
            stdin, stdout, stderr = ssh.exec_command('tail -20 /tmp/troubleshoot.log')
            print(stderr.read().decode())

        print("\n" + "="*60)
        print("  Deployment Complete!")
        print("="*60)
        print("URL: http://" + HOST + ":8088")
        print("Health: http://" + HOST + ":8088/api/health")
        print("="*60)

    except Exception as e:
        print("\n[ERROR] " + str(e))
        import traceback
        traceback.print_exc()

    finally:
        ssh.close()


if __name__ == '__main__':
    upload_files()
