import { copyFileSync, mkdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { spawnSync } from 'node:child_process'

const desktopDir = join(dirname(fileURLToPath(import.meta.url)), '..')
const repoDir = join(desktopDir, '..', '..')
const isWindows = process.platform === 'win32'
const npmCommand = isWindows ? process.env.ComSpec || 'cmd.exe' : 'npm'

function run(script) {
  const args = isWindows ? ['/d', '/s', '/c', `npm run ${script}`] : ['run', script]
  const result = spawnSync(npmCommand, args, {
    cwd: desktopDir,
    stdio: 'inherit',
  })

  if (result.error) throw result.error
  if (result.status !== 0) {
    process.exit(result.status ?? 1)
  }
}

run('full:build')
run('mini:build')

const releaseDir = join(desktopDir, 'release')
mkdirSync(releaseDir, { recursive: true })

const artifacts = [
  {
    source: join(desktopDir, 'src-tauri', 'target', 'release', 'senlinai-full.exe'),
    target: join(releaseDir, 'senlinai-full.exe'),
  },
  {
    source: join(repoDir, 'apps', 'mini', 'src-tauri', 'target', 'release', 'senlinai-mini.exe'),
    target: join(releaseDir, 'senlinai-mini.exe'),
  },
]

for (const artifact of artifacts) {
  copyFileSync(artifact.source, artifact.target)
  console.log(`Created ${artifact.target}`)
}
