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=20)
    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 where sqlite3 is
run("ls /www/wwwroot/ipzhinengti/node_modules/sqlite3 2>/dev/null && echo 'FOUND' || echo 'NOT FOUND'")
run("ls /www/wwwroot/ipzhinengti/node_modules/better-sqlite3 2>/dev/null && echo 'FOUND' || echo 'NOT FOUND'")

# Check db file
run("ls -la /www/wwwroot/ipzhinengti/data/ 2>/dev/null")

# Try running from the project dir
insert_db = r'''const sqlite3 = require('sqlite3');
const path = require('path');
const dbPath = path.join(__dirname, 'data', 'database.db');
console.log('DB path:', dbPath);
const db = new sqlite3.Database(dbPath);

const configs = [
    ['UPDATE_COS_BUCKET', 'xiazaigengxin-1417293730'],
    ['UPDATE_COS_REGION', 'ap-guangzhou'],
    ['UPDATE_COS_PATH', 'updates']
];

let done = 0;
configs.forEach(([key, value]) => {
    db.run(
        'INSERT OR REPLACE INTO system_config (config_key, config_value) VALUES (?, ?)',
        [key, value],
        (err) => {
            if (err) console.log('ERR:', key, err.message);
            else console.log('OK:', key, '=', value);
            done++;
            if (done === configs.length) {
                db.close();
                console.log('ALL DONE');
            }
        }
    );
});
'''

sftp = client.open_sftp()
with sftp.open('/www/wwwroot/ipzhinengti/insert_config.js', 'w') as f:
    f.write(insert_db)
sftp.close()

run("cd /www/wwwroot/ipzhinengti && node insert_config.js")
run("rm /www/wwwroot/ipzhinengti/insert_config.js")

# Restart
run("pm2 restart user-server 2>&1")
run("sleep 3 && curl -s http://localhost:3002/api/system/config/public")

client.close()
