#!/usr/bin/env node
/**
 * 在 pnpm install (postinstall) 时把 commit-msg hook 写入 .git/hooks/。
 * 已存在则覆盖（保持 source-of-truth 在 scripts/）。
 *
 * 在非 git 工作目录（如 CI 缓存还原阶段）静默退出，不报错。
 */
'use strict'

const fs = require('node:fs')
const path = require('node:path')
const { execSync } = require('node:child_process')

const repoRoot = path.resolve(__dirname, '..')

let commonDir
try {
  commonDir = execSync('git rev-parse --git-common-dir', {
    cwd: repoRoot,
    encoding: 'utf8',
  }).trim()
} catch (_err) {
  console.log('Not a git repository. Skipping hook install.')
  process.exit(0)
}

// commonDir 可能是相对路径，相对于 repoRoot
const absCommonDir = path.isAbsolute(commonDir) ? commonDir : path.join(repoRoot, commonDir)
const hookDir = path.join(absCommonDir, 'hooks')

if (!fs.existsSync(hookDir)) {
  try {
    fs.mkdirSync(hookDir, { recursive: true })
  } catch (_err) {
    console.log('Cannot create hook dir. Skipping.')
    process.exit(0)
  }
}

const hookPath = path.join(hookDir, 'commit-msg')
const hookContent = `#!/usr/bin/env bash
# Auto-generated by scripts/install-git-hooks.cjs — do not edit.
exec node "$(git rev-parse --show-toplevel)/scripts/check-progress-update.cjs" "$@"
`

try {
  fs.writeFileSync(hookPath, hookContent)
  fs.chmodSync(hookPath, 0o755)
  console.log('Installed commit-msg hook → scripts/check-progress-update.cjs')
} catch (err) {
  console.warn(`Failed to install commit-msg hook: ${err.message}`)
  // postinstall 不阻塞 pnpm install
  process.exit(0)
}
