import { execFileSync } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'

const DOC_FILES = [
  'docs/security/frontend-hardening.md',
  'docs/security/frontend-hardening.zh-CN.md',
  'docs/security/frontend-hardening.zh-CN.updates.md',
  'docs/security/atu-prod-hardening-playbook.zh-CN.md',
]

function printHelp() {
  console.log(`
用法:
  node scripts/sync-security-docs.js [source-ref]

说明:
  将安全文档从指定分支或提交同步到当前工作区。
  默认 source-ref 为 master。

示例:
  node scripts/sync-security-docs.js
  node scripts/sync-security-docs.js master
  node scripts/sync-security-docs.js origin/master
  npm run docs:sync:security -- master

注意:
  只有当 source-ref 中已经提交了这些文档时，才能成功同步。
`.trim())
}

function readFileFromGit(sourceRef, relativePath) {
  try {
    return execFileSync('git', ['show', `${sourceRef}:${relativePath}`], {
      encoding: 'utf8',
      maxBuffer: 10 * 1024 * 1024,
    })
  } catch (error) {
    const message = [
      `无法从 ${sourceRef} 读取 ${relativePath}。`,
      '请先确认源分支中已经提交了这些文档，再执行同步。',
    ].join('\n')
    throw new Error(message, { cause: error })
  }
}

function writeWorkspaceFile(relativePath, content) {
  const absolutePath = join(process.cwd(), relativePath)
  mkdirSync(dirname(absolutePath), { recursive: true })
  writeFileSync(absolutePath, content, 'utf8')
}

function main() {
  const sourceRef = process.argv[2] || 'master'

  if (sourceRef === '--help' || sourceRef === '-h') {
    printHelp()
    return
  }

  console.log(`开始从 ${sourceRef} 同步安全文档...`)

  for (const relativePath of DOC_FILES) {
    const content = readFileFromGit(sourceRef, relativePath)
    writeWorkspaceFile(relativePath, content)
    console.log(`已同步: ${relativePath}`)
  }

  console.log('安全文档同步完成。')
}

main()
