#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""重启 5.60 容器并验证健康状态"""
import paramiko, time

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.5.60', username='ubains', password='Ubains@123', timeout=30)

# 1. 重启容器
print(">>> docker restart plat-auto-test-app")
stdin, stdout, stderr = client.exec_command('docker restart plat-auto-test-app', timeout=180)
out = stdout.read().decode('utf-8', errors='replace').strip()
err = stderr.read().decode('utf-8', errors='replace').strip()[:200]
print(f"  result: {out or err}")
time.sleep(15)

# 2. 健康检查
print("\n>>> 健康检查")
for i in range(10):
    stdin2, stdout2, stderr2 = client.exec_command('curl -s http://localhost/health', timeout=30)
    out2 = stdout2.read().decode('utf-8', errors='replace').strip()
    if out2:
        print(f"  health({i+1}): {out2[:100]}")
        if 'healthy' in out2 or 'ok' in out2.lower() or '200' in out2:
            print("  ✅ 健康检查通过")
            break
    else:
        print(f"  ({i+1}) 无响应，等待5秒...")
    time.sleep(5)
else:
    print("  ❌ 健康检查未通过")

# 3. 容器状态
print("\n>>> 容器状态")
stdin3, stdout3, stderr3 = client.exec_command(
    "docker ps --filter name=plat-auto-test-app --format '{{.Names}} {{.Status}}'",
    timeout=30
)
print(f"  {stdout3.read().decode('utf-8', errors='replace').strip()}")

# 4. API 验证
print("\n>>> API 验证")
stdin4, stdout4, stderr4 = client.exec_command(
    'curl -s "http://localhost/api/device-sim/devices/stats?device_type=door"',
    timeout=30
)
out4 = stdout4.read().decode('utf-8', errors='replace').strip()
if out4:
    print(f"  设备统计: {out4[:120]}")
else:
    print("  ⚠️ 设备统计API无响应")

client.close()
print("\n✅ 部署验证完成")