import { exec, spawnSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import fs from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import url from 'node:url'
import prettier from 'prettier'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const root = path.resolve(__dirname, '..')
const syncedWorkspaces = new Map([
  [
    '@tailwindcss/oxide',
    [
      'crates/node/npm/android-arm-eabi',
      'crates/node/npm/android-arm64',
      'crates/node/npm/darwin-arm64',
      'crates/node/npm/darwin-x64',
      'crates/node/npm/freebsd-x64',
      'crates/node/npm/linux-arm-gnueabihf',
      'crates/node/npm/linux-arm64-gnu',
      'crates/node/npm/linux-arm64-musl',
      'crates/node/npm/linux-x64-gnu',
      'crates/node/npm/linux-x64-musl',
      'crates/node/npm/win32-x64-msvc',
    ],
  ],
  ['@tailwindcss/cli', ['packages/@tailwindcss-standalone']],
])
const inverseSyncedWorkspaces = new Map()
for (let [name, paths] of syncedWorkspaces) {
  for (let [idx, filePath] of paths.entries()) {
    
    paths[idx] = path.resolve(root, filePath, 'package.json')
    
    inverseSyncedWorkspaces.set(paths[idx], name)
  }
}
exec('pnpm --silent --filter=!./playgrounds/* -r exec pwd', async (err, stdout) => {
  if (err) {
    console.error(err)
    process.exit(1)
  }
  let paths = stdout
    .trim()
    .split('\n')
    .map((x) => path.resolve(x, 'package.json'))
    
    
    .filter((x) => !inverseSyncedWorkspaces.has(x))
  let workspaces = new Map()
  
  for (let path of paths) {
    let pkg = await fs.readFile(path, 'utf8').then(JSON.parse)
    if (pkg.private) continue
    workspaces.set(pkg.name, { version: pkg.version ?? '', path })
  }
  
  let lines = ['# Update the versions of the packages you want to change', '']
  for (let [name, info] of workspaces) {
    lines.push(`${name}: ${info.version}`)
  }
  let output = lines.join('\n')
  
  {
    
    
    
    
    
    let args = process.env.EDITOR.split(' ')
    let editor = args.shift()
    
    let filepath = path.resolve(tmpdir(), `version-${randomUUID()}.txt`)
    await fs.writeFile(filepath, output)
    
    
    spawnSync(editor, [...args, filepath], {
      stdio: 'inherit',
    })
    let newOutput = await fs.readFile(filepath, 'utf8').then((x) => x.trim().split('\n'))
    
    await fs.unlink(filepath)
    
    for (let line of newOutput) {
      if (line[0] === '#') continue 
      if (line.trim() === '') continue 
      let [name, version = ''] = line.split(':').map((x) => x.trim())
      
      
      let paths = [
        
        workspaces.get(name).path,
        
        
        ...(syncedWorkspaces.get(name) ?? []),
      ]
      for (let pkgPath of paths) {
        let pkg = await fs.readFile(pkgPath, 'utf8').then(JSON.parse)
        let name = pkg.name
        if (version !== '') {
          
          delete pkg.name
          delete pkg.version
          
          pkg = { name, version, ...pkg }
        }
        await fs.writeFile(
          pkgPath,
          await prettier
            .format(JSON.stringify(pkg, null, 2), { filepath: pkgPath })
            .then((x) => `${x.trim()}\n`),
        )
      }
    }
  }
  console.log('Done.')
})