import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('152.136.232.83', port=22, username='root', password='Jianhua105', timeout=10)

def run(cmd):
    print(f"\n>>> {cmd[:120]}")
    stdin, stdout, stderr = client.exec_command(cmd, timeout=15)
    out = stdout.read().decode('utf-8', errors='replace').strip()
    err = stderr.read().decode('utf-8', errors='replace').strip()
    if out: print(out[-600:])
    if err: print(f"ERR: {err[-200:]}")
    return out

# Write sysConfig with update COS settings
set_config = r'''const fs = require('fs');
const p = '/www/wwwroot/zhinengtiapp/data/sysConfig.json';
let cfg = {};
try { cfg = JSON.parse(fs.readFileSync(p, 'utf8')); } catch(e) {}
cfg.UPDATE_COS_BUCKET = 'xiazaigengxin-1417293730';
cfg.UPDATE_COS_REGION = 'ap-guangzhou';
cfg.UPDATE_COS_PATH = 'updates';
fs.writeFileSync(p, JSON.stringify(cfg, null, 2), 'utf8');
console.log('OK: sysConfig updated');
console.log(JSON.stringify(cfg, null, 2));
'''

sftp = client.open_sftp()
with sftp.open('/tmp/set_config.js', 'w') as f:
    f.write(set_config)
sftp.close()

run("node /tmp/set_config.js")

# Restart service
run("pm2 restart all 2>/dev/null || (pkill -f 'node.*zhinengtiapp' && sleep 1 && cd /www/wwwroot/zhinengtiapp && nohup node index.js > output.log 2>&1 &)")

# Test
run("sleep 3 && curl -s http://localhost:3002/api/system/config/public")

client.close()
print("\n=== DONE ===")
