import { execSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import readline from 'node:readline'
import SftpClient from 'ssh2-sftp-client'

const HOST = '92.53.106.114'
const USERNAME = 'cs21601'
const REMOTE_BASE = '/home/c/cs21601/quantum'
const LOCAL_DIST = path.resolve('./dist')
const LOCAL_SRC_ARCHIVE = path.resolve('./src.zip')
const DATE = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '');

(async () => {
  try {
    const password = await ask(`Введите пароль для ${USERNAME}@${HOST}: `)

    // 1) yarn build
    execSync('yarn build', { stdio: 'inherit' })

    // 2) git archive
    execSync(`git archive --format=zip --output=${LOCAL_SRC_ARCHIVE} main`, { stdio: 'inherit' })

    const sftp = new SftpClient()
    await sftp.connect({
      host: HOST,
      port: 22,
      username: USERNAME,
      password,
    })

    // 3) Переименование public_html
    try {
      await sftp.rename(`${REMOTE_BASE}/public_html`, `${REMOTE_BASE}/public_html_${DATE}`)
      console.log('✅ Папка public_html переименована')
    }
    catch {
      console.log('⚠️ public_html не найдена, пропускаю переименование')
    }

    // 4) Загрузка dist
    await sftp.mkdir(`${REMOTE_BASE}/public_html`, true)
    await uploadDir(sftp, LOCAL_DIST, `${REMOTE_BASE}/public_html`)

    // 5) Загрузка src.zip
    await sftp.mkdir(`${REMOTE_BASE}/src`, true)
    await sftp.put(LOCAL_SRC_ARCHIVE, `${REMOTE_BASE}/src.zip`)

    await sftp.end()
    console.log('🎉 Деплой завершён успешно!')
  }
  catch (err) {
    console.error('❌ Ошибка деплоя:', err.message)
    process.exit(1)
  }
})()

function ask(query) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  })
  return new Promise((resolve) => {
    rl.question(query, (value) => {
      rl.close()
      resolve(value)
    })
  })
}

async function uploadDir(sftp, localDir, remoteDir) {
  const items = fs.readdirSync(localDir)
  for (const item of items) {
    const localPath = path.join(localDir, item)
    const remotePath = `${remoteDir}/${item}`
    if (fs.lstatSync(localPath).isDirectory()) {
      await sftp.mkdir(remotePath, true)
      await uploadDir(sftp, localPath, remotePath)
    }
    else {
      await sftp.put(localPath, remotePath)
    }
  }
}
