import fs from 'node:fs'
import path from 'node:path'
import { execSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const distDir = path.join(root, 'dist')
const outRoot = path.join(root, 'packages')
const version = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version
const input = process.argv[2]
const targets = input === 'all' ? ['chrome', 'edge', 'firefox'] : [input]

if (!input || !['chrome', 'edge', 'firefox', 'all'].includes(input)) {
  console.error('usage: node scripts/build-platform.mjs <chrome|edge|firefox|all>')
  process.exit(1)
}

if (!fs.existsSync(distDir)) {
  console.error('dist not found. run npm run build first.')
  process.exit(1)
}

fs.mkdirSync(outRoot, { recursive: true })

function rmrf(target) {
  fs.rmSync(target, { recursive: true, force: true })
}

function copyDir(from, to) {
  fs.mkdirSync(to, { recursive: true })
  for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
    const src = path.join(from, entry.name)
    const dst = path.join(to, entry.name)
    if (entry.isDirectory()) copyDir(src, dst)
    else fs.copyFileSync(src, dst)
  }
}

function patchManifest(targetDir, platform) {
  const manifestPath = path.join(targetDir, 'manifest.json')
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))

  manifest.name = 'Gomdown Helper'
  manifest.short_name = 'Gomdown'

  if (platform === 'firefox') {
    manifest.browser_specific_settings = {
      gecko: {
        id: 'gomdown-helper@projectdx',
      },
    }
    if (manifest.background && manifest.background.type) {
      delete manifest.background.type
    }
  } else {
    delete manifest.browser_specific_settings
  }

  fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
}

for (const platform of targets) {
  const stageDir = path.join(outRoot, `${platform}`)
  rmrf(stageDir)
  copyDir(distDir, stageDir)
  patchManifest(stageDir, platform)

  const zipName = `gomdown-helper.v${version}.${platform}.zip`
  const zipPath = path.join(outRoot, zipName)
  rmrf(zipPath)
  execSync(`cd ${JSON.stringify(stageDir)} && zip -qr ${JSON.stringify(zipPath)} .`)
  console.log(`built: ${zipPath}`)
}
