import { readFileSync } from 'node:fs'
import path from 'node:path'
import pico from 'picocolors'

const msgPath = path.resolve('.git/COMMIT_EDITMSG')
const msg = readFileSync(msgPath, 'utf-8').trim()

const commitRE
  = /^(revert: )?(feat|fix|docs|style|refactor|perf|test|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
  console.log()
  console.error(
    `  ${pico.white(pico.bgRed(' ERROR '))} ${pico.red(
      `invalid commit message format.`,
    )}\n\n${
      pico.red(
        `  Proper commit message format is required for automated changelog generation. Examples:\n\n`,
      )
    }    ${pico.green(`feat(components): add ApiCheckboxGroup component`)}\n`
    + `    ${pico.green(
      `fix(components/Form): ImageUpload type error (close #28)`,
    )}\n\n${
      pico.red(`\n`)}`,
  )
  process.exit(1)
}