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');

  const checks = [
    ['SRTM файлов', 'ls /home/slin/enduro-trails/data/srtm/*.hgt 2>/dev/null | wc -l'],
    ['terrain/hypso PNG', 'find /home/slin/enduro-trails/data/terrain/hypso -name "*.png" 2>/dev/null | wc -l'],
    ['terrain/hillshade PNG', 'find /home/slin/enduro-trails/data/terrain/hillshade -name "*.png" 2>/dev/null | wc -l'],
    ['nginx terrain config', 'grep -r "terrain" /etc/nginx/sites-enabled/ /etc/nginx/conf.d/ 2>/dev/null | head -5'],
    ['nginx status', 'systemctl is-active nginx 2>/dev/null || echo unknown'],
    ['terrain curl hypso z8', 'curl -o /dev/null -s -w "%{http_code}" "https://openclaw.mva154.duckdns.org/enduro/terrain/hypso/8/75/42.png" 2>/dev/null || echo "no curl"'],
    ['disk usage terrain', 'du -sh /home/slin/enduro-trails/data/terrain/ 2>/dev/null || echo "not found"'],
    ['disk usage srtm', 'du -sh /home/slin/enduro-trails/data/srtm/ 2>/dev/null || echo "not found"'],
    ['running processes gdal', 'pgrep -a gdal 2>/dev/null || echo "none"'],
    ['running processes python', 'pgrep -a python3 2>/dev/null | grep -v "pgrep" | head -5 || echo "none"'],
    ['app.js terrain-toggle', 'grep -c "terrain-toggle" /home/slin/enduro-trails/prototype/static/app.js 2>/dev/null || echo "0"'],
    ['index.html terrain-toggle', 'grep -c "terrain-toggle" /home/slin/enduro-trails/prototype/static/index.html 2>/dev/null || echo "0"'],
    ['container app.js terrain', 'docker exec prototype-enduro-trails-1 grep -c "terrain-toggle" /app/static/app.js 2>/dev/null || echo "0"'],
  ];

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

  conn.end();
});

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

conn.connect(config);
