import { execFileSync } from 'node:child_process'
import { readFileSync, writeFileSync } from 'node:fs'

import { resolveReleasePlan } from './release-version.mjs'

function readPackageJson() {
  return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
}

function writePackageJson(pkg) {
  const packageJsonUrl = new URL('../package.json', import.meta.url)
  writeFileSync(packageJsonUrl, `${JSON.stringify(pkg, null, 2)}\n`)
}

function getLatestTagVersion() {
  const output = execFileSync('git', ['tag', '--sort=-v:refname'], {
    encoding: 'utf8',
  })

  return output
    .split('\n')
    .map(tag => tag.trim())
    .find(tag => /^v?\d+\.\d+\.\d+(?:[-+].*)?$/.test(tag)) ?? null
}

function run() {
  const pkg = readPackageJson()
  const latestTagVersion = getLatestTagVersion()
  const plan = resolveReleasePlan(pkg.version, latestTagVersion)

  if (pkg.version !== plan.syncedPackageVersion) {
    pkg.version = plan.syncedPackageVersion
    writePackageJson(pkg)
  }

  const changelogenArgs = ['changelogen', '--release']

  if (plan.releaseVersion) {
    changelogenArgs.push('-r', plan.releaseVersion)
  }

  execFileSync('./node_modules/.bin/changelogen', changelogenArgs.slice(1), {
    stdio: 'inherit',
  })
  execFileSync('npm', ['publish'], { stdio: 'inherit' })
  execFileSync('git', ['push', '--follow-tags'], { stdio: 'inherit' })
}

run()
