#!/usr/bin/env bash
# verify_references.sh — 활성 운영 문서의 참조 경로 무결성 감사
# 감사 대상 (활성 운영):
#   - 공유/PD_지시_트래킹/*.md
#   - 공유/소통/*→PM/*.md, */PM→*/*.md (완료/ 제외)
#   - 공유/조직공지/*.md (2026-04-17 이후만)
# 제외 (역사 기록·완료 아카이브·Placeholder·Glob):
#   - 공유/소통/완료/, 공유/대화로그/
#   - YYYY-MM-DD·{·}·$()·괄호··(한글 중점)
#   - 폐기된 용어: 일일보고/, 공통_업무_규칙, .claude/live/, 개발실/기획실
set -u
cd "$(dirname "$0")/.."

scan_dirs=(
  "공유/PD_지시_트래킹"
  "공유/조직공지"
)
# 소통 허브는 완료/ 제외하고 활성 inbox만
inbox_dirs=(
  "공유/소통/개발팀→PM"
  "공유/소통/기획팀→PM"
  "공유/소통/PM→개발팀"
  "공유/소통/PM→기획팀"
  "공유/소통/개발팀→기획팀"
  "공유/소통/기획팀→개발팀"
  "공유/소통/pm-auditor→PM"
  "공유/소통/dev-auditor→PM"
  "공유/소통/plan-auditor→PM"
)

exclude_patterns='(공유/일일보고|공통_업무_규칙\.md|\.claude/live/|개발실/|기획실/|PM↔개발실|PM↔기획실|개발실↔기획실|/\{|YYYY-MM-DD|XXXX-XX-XX|2026-XX|\$\(|·|\(|개발\+기획|/로$|scripts/pd_log_active_scan|scripts/agent_call_log|scripts/post_commit|scripts/post_tool_validate|scripts/session_end_sync|scripts/commit_log_match|공유/세션_현황|feedback_pm_context_hook_gap|feedback_session_command_brevity|feedback_session_delivery_omission|feedback_setup_verification|memory/feedback_pm_context_restoration_failure|공유/시뮬결과|공유/개발팀→기획팀/|공유/기획팀→개발팀/|공유/완료/|공유/운영기록|코어코드/EerieVillage_서버)'

total_missing=0

audit_file() {
  local src="$1"
  grep -nE '(공유|프로젝트|코어코드|\.claude|scripts|memory)/[^[:space:]`)"<>|,]+' "$src" 2>/dev/null | while IFS=: read -r lnum rest; do
    echo "$rest" | grep -oE '(공유|프로젝트|코어코드|\.claude|scripts|memory)/[^[:space:]`)"<>|,]+' | while IFS= read -r path; do
      path="${path%[.,;:\)]}"
      [[ "$path" == *"**"* ]] && continue
      [[ "$path" =~ ^[a-f0-9]{7,40}$ ]] && continue
      echo "$path" | grep -qE "$exclude_patterns" && continue
      [ -e "$path" ] && continue
      [ -e "$path/" ] && continue
      echo "  [$src:$lnum] $path"
    done
  done
}

for d in "${scan_dirs[@]}"; do
  [ -d "$d" ] || continue
  while IFS= read -r f; do audit_file "$f"; done < <(find "$d" -maxdepth 3 -name '*.md' 2>/dev/null)
done

for d in "${inbox_dirs[@]}"; do
  [ -d "$d" ] || continue
  while IFS= read -r f; do audit_file "$f"; done < <(find "$d" -maxdepth 1 -name '*.md' 2>/dev/null)
done

if [ "$total_missing" -eq 0 ]; then
  out=$(for d in "${scan_dirs[@]}" "${inbox_dirs[@]}"; do
    [ -d "$d" ] || continue
    while IFS= read -r f; do audit_file "$f"; done < <(find "$d" -maxdepth 3 -name '*.md' 2>/dev/null)
  done)
  if [ -z "$out" ]; then
    echo "✅ [참조 무결성 감사] 활성 운영 영역 부재 경로 0건"
  fi
fi
