import { exec } from 'node:child_process'
import { promisify } from 'node:util'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { access } from 'node:fs/promises'
import consola from 'consola'

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

async function checkPlatformExists(platform: string): Promise<boolean> {
  try {
    await access(join(root, 'platforms', platform))
    return true
  } catch {
    return false
  }
}

async function addPlatform(platform: string) {
  try {
    // 检查平台是否已存在
    const exists = await checkPlatformExists(platform)
    if (exists) {
      consola.info(`Platform ${platform} already exists`)
      return
    }

    // 添加平台
    consola.info(`Adding ${platform} platform...`)
    const { stdout, stderr } = await execAsync(`cordova platform add ${platform}`, {
      cwd: root,
      env: {
        ...process.env,
        NODE_ENV: 'development'
      }
    })

    if (stderr) {
      consola.warn(stderr)
    }

    if (stdout) {
      consola.info(stdout)
    }

    consola.success(`Platform ${platform} added successfully`)
  } catch (error) {
    if (error instanceof Error) {
      consola.error('Failed to add platform:', error.message)
    } else {
      consola.error('An unknown error occurred while adding platform')
    }
    process.exit(1)
  }
}

async function main() {
  try {
    // 添加 Android 平台
    await addPlatform('android')
  } catch (error) {
    if (error instanceof Error) {
      consola.error('Platform addition failed:', error.message)
    } else {
      consola.error('An unknown error occurred')
    }
    process.exit(1)
  }
}

main() 