import { mkdir, copyFile, access } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import consola from 'consola'

const __dirname = fileURLToPath(new URL('.', import.meta.url))
const root = join(__dirname, '..')

// 检查文件是否存在的辅助函数
async function fileExists(path: string): Promise<boolean> {
  try {
    await access(path)
    return true
  } catch {
    return false
  }
}

async function main() {
  // 确保 dist 目录存在
  try {
    await mkdir(join(root, 'dist'))
    consola.info('dist directory created')
  } catch (err) {
    consola.info('dist directory already exists')
  }

  // 定义 APK 文件路径
  const apkPaths = {
    debug: {
      source: join(root, 'platforms/android/app/build/outputs/apk/debug/app-debug.apk'),
      target: join(root, 'dist/app-debug.apk')
    },
    release: {
      source: join(root, 'platforms/android/app/build/outputs/apk/release/app-release.apk'),
      target: join(root, 'dist/app-release.apk')
    }
  }

  // 尝试复制 debug 和 release 版本的 APK
  for (const [type, paths] of Object.entries(apkPaths)) {
    if (await fileExists(paths.source)) {
      try {
        await copyFile(paths.source, paths.target)
        consola.success(`${type} APK copied to dist/app-${type}.apk`)
      } catch (err) {
        consola.warn(`Failed to copy ${type} APK:`, err)
      }
    } 
  }
}

main()
