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

const TILES = [
  'N55E037','N55E038','N55E039','N55E040',
  'N54E037','N54E038','N54E039','N54E040',
  'N53E038','N53E039','N53E040','N53E041',
  'N52E038','N52E039','N52E040','N52E041',
  'N56E037','N56E038','N56E039','N56E040',
  'N57E037','N57E038','N57E039','N57E040',
  'N58E037','N58E038','N58E039','N58E040',
  'N59E038','N59E039','N59E040','N59E041',
  'N60E040','N60E041','N60E042',
  'N54E042','N54E043','N54E044','N54E045',
  'N53E042','N53E043','N53E044','N53E045',
  'N52E042','N52E043','N52E044','N52E045',
  'N51E038','N51E039','N51E040','N51E041',
  'N50E038','N50E039','N50E040','N50E041',
  'N55E047','N55E048','N55E049','N55E050',
  'N54E047','N54E048','N54E049','N54E050',
  'N56E047','N56E048','N56E049','N56E050',
];

const conn = new Client();

conn.on('ready', () => {
  console.log('SSH connected. Downloading with retry...');

  let completed = 0;
  let failed = 0;
  let skipped = 0;

  function downloadNext(idx) {
    if (idx >= TILES.length) {
      console.log(`\n=== DONE === Completed: ${completed}, Skipped: ${skipped}, Failed: ${failed}`);
      conn.end();
      return;
    }

    const tile = TILES[idx];
    const lat = tile.substring(1, 3);
    const url = `https://s3.amazonaws.com/elevation-tiles-prod/skadi/${lat}/${tile}.hgt.gz`;
    const remoteHgt = `/home/slin/enduro-trails/data/srtm/${tile}.hgt`;
    const remoteGz = `/home/slin/enduro-trails/data/srtm/${tile}.hgt.gz`;

    // Check if already exists
    conn.exec(`test -f ${remoteHgt} && echo EXISTS || echo MISSING`, (err, stream) => {
      if (err) { failed++; downloadNext(idx + 1); return; }
      let out = '';
      stream.on('data', d => out += d);
      stream.on('close', () => {
        if (out.trim() === 'EXISTS') {
          skipped++;
          console.log(`[${idx+1}/${TILES.length}] SKIP ${tile} (exists)`);
          downloadNext(idx + 1);
          return;
        }

        // Download WITHOUT -q flag to see errors
        const cmd = `cd /home/slin/enduro-trails/data/srtm && wget --timeout=60 "${url}" -O ${remoteGz} 2>&1 | tail -3 && test -s ${remoteGz} && echo DL_OK || echo DL_FAIL`;

        conn.exec(cmd, (err, stream) => {
          if (err) { failed++; downloadNext(idx + 1); return; }
          let out2 = '';
          stream.on('data', d => out2 += d);
          stream.on('close', () => {
            const lines = out2.trim().split('\n');
            const lastLine = lines[lines.length - 1] || '';
            if (lastLine !== 'DL_OK') {
              failed++;
              console.log(`[${idx+1}/${TILES.length}] FAIL ${tile}`);
              // Clean up failed download
              conn.exec(`rm -f ${remoteGz}`, () => {});
              downloadNext(idx + 1);
              return;
            }

            // Extract
            conn.exec(`cd /home/slin/enduro-trails/data/srtm && gunzip -f ${remoteGz} && test -f ${remoteHgt} && echo EX_OK || echo EX_FAIL`, (err, stream) => {
              if (err) { failed++; downloadNext(idx + 1); return; }
              let out3 = '';
              stream.on('data', d => out3 += d);
              stream.on('close', () => {
                const exResult = out3.trim();
                if (exResult === 'EX_OK') {
                  completed++;
                  console.log(`[${idx+1}/${TILES.length}] OK ${tile}`);
                } else {
                  failed++;
                  console.log(`[${idx+1}/${TILES.length}] FAIL ${tile} (extract)`);
                }
                downloadNext(idx + 1);
              });
            });
          });
        });
      });
    });
  }

  downloadNext(0);
});

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

conn.connect({
  host: '82.22.50.71',
  username: 'slin',
  password: 'motoZ@yaz2010',
  readyTimeout: 30000
});
