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

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 = '', err2 = '';
      stream.on('data', d => out += d);
      stream.stderr.on('data', d => err2 += d);
      stream.on('close', () => resolve({ out: out.trim(), err: err2.trim() }));
    });
  });
}

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

  // Диагностика 404
  const checks = [
    ['nginx terrain location', 'grep -A5 "terrain" /etc/nginx/sites-enabled/openclaw.mva154.duckdns.org'],
    ['права на terrain dir', 'ls -la /home/slin/enduro-trails/data/terrain/'],
    ['права на hypso dir', 'ls -la /home/slin/enduro-trails/data/terrain/hypso/ | head -5'],
    ['nginx user', 'ps aux | grep nginx | grep -v grep | head -2'],
    ['тайл z8 существует', 'ls /home/slin/enduro-trails/data/terrain/hypso/8/ 2>/dev/null | head -5 || echo "нет директории z8"'],
    ['nginx error log', 'tail -5 /var/log/nginx/error.log 2>/dev/null || echo "нет доступа"'],
    ['nginx access log terrain', 'tail -5 /var/log/nginx/access.log 2>/dev/null | grep terrain || echo "нет terrain запросов"'],
    ['curl verbose', 'curl -sv "https://openclaw.mva154.duckdns.org/enduro/terrain/hypso/8/75/42.png" 2>&1 | grep -E "< HTTP|Location|< location" | head -5'],
  ];

  for (const [label, cmd] of checks) {
    const r = await exec(conn, cmd);
    console.log(`\n=== ${label} ===`);
    console.log(r.out || r.err || '(empty)');
  }

  conn.end();
});

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

conn.connect(config);
