import { databaseBackup } from '@d8d/server/utils/backup'
import { promises as fs } from 'fs'
import path from 'path'
import process from 'node:process'

const BACKUP_DIR = process.env.BACKUP_DIR || './backups'

async function main() {
  const command = process.argv[2]

  switch (command) {
    case 'backup':
      await databaseBackup.createBackup()
      break
    case 'restore':
      const backupFile = process.argv[3]
      if (!backupFile) {
        console.error('请指定要恢复的备份文件')
        process.exit(1)
      }
      // 如果备份文件不包含路径，则在备份目录中查找
      const fullBackupPath = backupFile.includes('/') ? backupFile : path.join(BACKUP_DIR, backupFile)
      await databaseBackup.restoreBackup(fullBackupPath)
      break
    case 'cleanup':
      await databaseBackup.cleanupOldBackups()
      break
    case 'list':
      const files = await fs.readdir(BACKUP_DIR)
      const backupFiles = files.filter(f => f.endsWith('.dump'))
      console.log('可用备份文件:')
      backupFiles.forEach(file => console.log(`  - ${file}`))
      break
    case 'latest':
      const latestFiles = await fs.readdir(BACKUP_DIR)
      const latestBackupFiles = latestFiles.filter(f => f.endsWith('.dump')).sort().reverse()
      if (latestBackupFiles.length > 0) {
        console.log(latestBackupFiles[0])
      } else {
        console.log('没有找到备份文件')
      }
      break
    default:
      console.log('用法: node backup.ts [backup|restore <file>|cleanup|list]')
      process.exit(1)
  }
}

main().catch(console.error)