import fg from 'fast-glob'
import fs from 'fs-extra'
import { join, resolve } from 'path'
import { packages } from './utils/packages'
import { run } from './utils/process'
import { version } from '../package.json'

const FILES_COPY_LOCAL = ['README.md', '*.js', '*.mjs', '*.d.ts', 'types/*.d.ts']

async function copyFiles() {
  for (const { name } of packages) {
    const packageRoot = resolve(__dirname, '..', 'packages', name)
    const packageDist = resolve(packageRoot, 'dist')

    const files = await fg(FILES_COPY_LOCAL, { cwd: packageRoot })
    for (const file of files) {
      await fs.copy(join(packageRoot, file), join(packageDist, file), { recursive: true })
    }

    const packageJSON = await fs.readJSON(join(packageRoot, 'package.json'))
    for (const key of Object.keys(packageJSON.dependencies || {})) {
      if (key.startsWith('@datago/')) {
        packageJSON.dependencies[key] = version
      }
    }
    await fs.writeJSON(join(packageDist, 'package.json'), packageJSON, { spaces: 2 })
  }
}

async function build() {
  await run('pnpm run clean')

  await run('pnpm run build:rollup')

  await run('pnpm run build:component')

  await run('pnpm run build:css')

  await run('pnpm run build:theme')

  await copyFiles()
}

async function cli() {
  try {
    await build()
  } catch (e) {
    console.error(e)
    process.exit(1)
  }
}

export { build }

if (require.main === module) cli()
