const { Client } = require('ssh2');
const fs = require('fs');
const path = require('path');

const conn = new Client();
const config = {
  host: '82.22.50.71',
  username: 'slin',
  password: 'motoZ@yaz2010',
  readyTimeout: 30000
};

function exec(conn, cmd) {
  return new Promise((resolve, reject) => {
    conn.exec(cmd, (err, stream) => {
      if (err) return reject(err);
      let out = '', e = '';
      stream.on('data', d => out += d);
      stream.stderr.on('data', d => e += d);
      stream.on('close', () => resolve({ out: out.trim(), err: e.trim() }));
    });
  });
}

function sftp_put(sftp, localPath, remotePath) {
  return new Promise((resolve, reject) => {
    sftp.fastPut(localPath, remotePath, (err) => {
      if (err) reject(err); else resolve();
    });
  });
}

conn.on('ready', async () => {
  console.log('✅ Connected');

  conn.sftp(async (err, sftp) => {
    if (err) { console.error('SFTP error:', err); conn.end(); return; }

    // 1. Загрузить app.py
    const localApp = path.join(__dirname, 'app.py');
    const remoteApp = '/home/slin/enduro-trails/prototype/app.py';
    console.log('📤 Uploading app.py...');
    await sftp_put(sftp, localApp, remoteApp);
    console.log('✅ app.py uploaded');

    // 2. docker cp app.py в контейнер
    const cp = await exec(conn, 'docker cp /home/slin/enduro-trails/prototype/app.py prototype-enduro-trails-1:/app/app.py');
    console.log('docker cp app.py:', cp.out || cp.err || 'ok');

    // 3. Рестарт контейнера
    console.log('🔄 Restarting container...');
    const restart = await exec(conn, 'docker restart prototype-enduro-trails-1');
    console.log('restart:', restart.out || restart.err);

    // 4. Подождать 8 сек
    await new Promise(r => setTimeout(r, 8000));

    // 5. docker cp статики после рестарта
    const cpJs = await exec(conn, 'docker cp /home/slin/enduro-trails/prototype/static/app.js prototype-enduro-trails-1:/app/static/app.js');
    console.log('docker cp app.js:', cpJs.out || cpJs.err || 'ok');
    const cpCss = await exec(conn, 'docker cp /home/slin/enduro-trails/prototype/static/app.css prototype-enduro-trails-1:/app/static/app.css');
    console.log('docker cp app.css:', cpCss.out || cpCss.err || 'ok');
    const cpHtml = await exec(conn, 'docker cp /home/slin/enduro-trails/prototype/static/index.html prototype-enduro-trails-1:/app/static/index.html');
    console.log('docker cp index.html:', cpHtml.out || cpHtml.err || 'ok');

    // 6. Проверить terrain endpoint
    await new Promise(r => setTimeout(r, 3000));
    const http = await exec(conn, 'curl -o /dev/null -s -w "%{http_code}" "https://openclaw.mva154.duckdns.org/enduro/terrain/hypso/8/75/42.png"');
    console.log('\n🌐 HTTP terrain hypso z8:', http.out);

    const http2 = await exec(conn, 'curl -o /dev/null -s -w "%{http_code}" "http://localhost:5558/terrain/hypso/8/75/42.png"');
    console.log('🌐 HTTP direct FastAPI:', http2.out);

    sftp.end();
    conn.end();
  });
});

conn.on('error', err => { console.error('❌', err.message); process.exit(1); });
conn.connect(config);
