const COMMIT_MENTION_PREFIX = 'git:commit:'
const COMMIT_ID_RE = /^[0-9a-f]{7,40}$/i
const COMMIT_OBJECT_PATH_RE
  = /(?:^|[\\/])\.git[\\/]+objects[\\/]+([0-9a-f]{2})[\\/]+([0-9a-f]{7,40})$/i

export function getCommitIdFromMention(value: string): string | null {
  const raw = String(value || '')
  if (!raw.startsWith(COMMIT_MENTION_PREFIX))
    return null
  const sha = raw.slice(COMMIT_MENTION_PREFIX.length).trim()
  if (!COMMIT_ID_RE.test(sha))
    return null
  return sha
}

export function isCommitMention(value: string): boolean {
  return Boolean(getCommitIdFromMention(value))
}

export function formatCommitObjectPath(sha: string): string {
  const safe = String(sha || '').trim()
  if (!safe)
    return ''
  return `.git/objects/${safe.slice(0, 2)}/${safe}`
}

export function getCommitIdFromObjectPath(path: string): string | null {
  const raw = String(path || '').trim()
  if (!raw)
    return null
  const match = raw.match(COMMIT_OBJECT_PATH_RE)
  if (!match)
    return null
  const dir = String(match[1] ?? '').toLowerCase()
  const sha = String(match[2] ?? '').toLowerCase()
  if (!COMMIT_ID_RE.test(sha))
    return null
  if (dir && !sha.startsWith(dir))
    return null
  return sha
}

export function renderCommitMarkdownLink(sha: string): string {
  const safe = String(sha || '').trim()
  if (!safe)
    return ''
  const path = formatCommitObjectPath(safe)
  return `[${safe}](${path})`
}

export function buildCommitMentionValue(sha: string): string {
  const safe = String(sha || '').trim()
  if (!safe)
    return ''
  return `${COMMIT_MENTION_PREFIX}${safe}`
}
