import paramiko, json

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

# Check current sys_config.json (correct filename)
run("cat /www/wwwroot/zhinengtiapp/data/sys_config.json 2>/dev/null || echo 'FILE NOT FOUND'")

# Check wrong filename
run("cat /www/wwwroot/zhinengtiapp/data/sysConfig.json 2>/dev/null || echo 'FILE NOT FOUND'")

# Write to the CORRECT file: sys_config.json
set_config = r'''const fs = require('fs');
const p = '/www/wwwroot/zhinengtiapp/data/sys_config.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: sys_config.json updated');
console.log(JSON.stringify(cfg, null, 2));
'''

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

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

# Restart to pick up changes
run("pm2 restart ai-video 2>&1")
run("sleep 3 && pm2 list")

# Test endpoint
run("curl -s http://localhost:3001/api/system/config/public")

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