#!/usr/bin/env bash
# PostToolUse(Edit/Write/MultiEdit) Hook example
# Purpose: warn/block when Korean Markdown bold syntax is likely to render badly.

set -uo pipefail

input="$(cat)"
file_path="$(printf '%s' "$input" | jq -r '.tool_input.file_path // ""' 2>/dev/null)"

if [ -z "$file_path" ] || [[ ! "$file_path" =~ \.(md|mdx)$ ]] || [ ! -f "$file_path" ]; then
  printf '%s' "$input"
  exit 0
fi

cleaned="$(
  awk '
    BEGIN { in_block = 0 }
    /^```/ { in_block = !in_block; next }
    !in_block {
      line = $0
      while (match(line, /`[^`]*`/)) {
        line = substr(line, 1, RSTART - 1) substr(line, RSTART + RLENGTH)
      }
      gsub(/"\*\*[^"*]+\*\*"/, "", line)
      print NR ":" line
    }
  ' "$file_path"
)"

issues=""

quote_issues="$(printf '%s\n' "$cleaned" | grep -E '\*\*"[^"*]+"\*\*' 2>/dev/null || true)"
if [ -n "$quote_issues" ]; then
  issues="${issues}
[pattern: bold marker wraps quotation marks]
${quote_issues}
"
fi

particle_issues="$(printf '%s\n' "$cleaned" | grep -E '\*\*[^*]*\([^)]*\)\*\*[가-힣]' 2>/dev/null || true)"
if [ -n "$particle_issues" ]; then
  issues="${issues}
[pattern: bold marker wraps parentheses and is followed by Korean particle]
${particle_issues}
"
fi

if [ -z "$issues" ]; then
  printf '%s' "$input"
  exit 0
fi

{
  echo ""
  echo "[hook] Korean Markdown bold pattern needs review: ${file_path}"
  printf '%s\n' "$issues"
  echo "Fix examples:"
  echo '  **"텍스트"** -> "**텍스트**"'
  echo '  **이름(설명)**은 -> **이름** (설명)은'
  echo ""
} >&2

exit 2

