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
};

const staticDir = path.join(__dirname, 'static');
const remoteDir = '/home/slin/enduro-trails/prototype/static/';
const containerName = 'prototype-enduro-trails-1';

console.log('🔌 Connecting to server...');

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

  conn.sftp((err, sftp) => {
    if (err) {
      console.error('❌ SFTP error:', err);
      conn.end();
      process.exit(1);
    }

    // Upload index.html
    console.log('📤 Uploading index.html...');
    const indexStream = sftp.createWriteStream(remoteDir + 'index.html');
    fs.createReadStream(path.join(staticDir, 'index.html')).pipe(indexStream);

    indexStream.on('close', () => {
      console.log('✅ index.html uploaded');

      // Upload app.css
      console.log('📤 Uploading app.css...');
      const cssStream = sftp.createWriteStream(remoteDir + 'app.css');
      fs.createReadStream(path.join(staticDir, 'app.css')).pipe(cssStream);

      cssStream.on('close', () => {
        console.log('✅ app.css uploaded');

        // docker compose restart
        console.log('🔄 Restarting container via docker compose...');
        conn.exec('cd /home/slin/enduro-trails/prototype && docker compose restart', (err, stream) => {
          if (err) {
            console.error('❌ docker compose restart error:', err);
            conn.end();
            process.exit(1);
          }

          let out = '';
          stream.on('data', d => out += d.toString());
          stream.stderr.on('data', d => out += d.toString());

          stream.on('close', code => {
            console.log('docker compose restart output:', out.trim());
            if (code !== 0) {
              console.error('❌ docker compose restart failed (code ' + code + ')');
              conn.end();
              process.exit(1);
            }
            console.log('✅ Container restarted');

            // Wait 8 seconds then docker cp
            console.log('⏳ Waiting 8s for container to come up...');
            setTimeout(() => {
              const cpCmd = [
                `docker cp ${remoteDir}index.html ${containerName}:/app/static/index.html`,
                `docker cp ${remoteDir}app.css ${containerName}:/app/static/app.css`
              ].join(' && ');

              console.log('📦 Copying files into container...');
              conn.exec(cpCmd, (err, stream) => {
                if (err) {
                  console.error('❌ docker cp error:', err);
                  conn.end();
                  process.exit(1);
                }

                let cpOut = '';
                stream.on('data', d => cpOut += d.toString());
                stream.stderr.on('data', d => cpOut += d.toString());

                stream.on('close', code => {
                  if (code !== 0) {
                    console.error('❌ docker cp failed:', cpOut);
                    conn.end();
                    process.exit(1);
                  }
                  console.log('✅ Files copied into container');
                  console.log('🎉 Deploy complete!');
                  conn.end();
                });
              });
            }, 8000);
          });
        });
      });

      cssStream.on('error', err => {
        console.error('❌ app.css upload error:', err);
        conn.end();
        process.exit(1);
      });
    });

    indexStream.on('error', err => {
      console.error('❌ index.html upload error:', err);
      conn.end();
      process.exit(1);
    });
  });
});

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

conn.connect(config);
