#!/usr/bin/env bash
# Reindex: regenerate wiki/INDEX.md from wiki/**/*.md frontmatter.
# Usage: scripts/reindex.sh
# 借鉴 Claude Opus 的 AGENTS.md 思路：一行一条目 [标题](相对路径) — hook，
# agent 先 skim 再打开文件。INDEX.md 由本脚本生成，不要手改。
set -euo pipefail

KB_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WIKI_DIR="$KB_ROOT/wiki"
INDEX_FILE="$WIKI_DIR/INDEX.md"
TMP_FILE="$WIKI_DIR/.INDEX.tmp"

# 固定顺序的 section；不存在或没有 .md 的自动跳过
SECTIONS="investing tech life decisions"

{
  echo "# Wiki Index"
  echo
  echo "> 自动生成（scripts/reindex.sh）— 不要手改。每行一个条目：[标题](相对路径) — 正文首行摘要"
  echo
  echo "用法：skim 找相关条目 → 打开对应文件看细节。新页面 reindex 后自动出现。"
  echo

  for section in $SECTIONS; do
    dir="$WIKI_DIR/$section"
    [ -d "$dir" ] || continue

    # 先数文件，空 section 不输出标题
    count=0
    while IFS= read -r _; do
      count=$((count + 1))
    done < <(find "$dir" -maxdepth 1 -name '*.md' -type f ! -name '_template.md' ! -name 'README.md' | sort)
    [ "$count" -gt 0 ] || continue

    echo "## $section"
    echo

    while IFS= read -r f; do
      rel="${f#"$WIKI_DIR"/}"

      # frontmatter title（可带引号），缺省用文件名
      title="$(awk -F': ' '/^title:/ { gsub(/^"/,"",$2); gsub(/"$/,"",$2); print $2; exit }' "$f")"
      [ -n "$title" ] || title="$(basename "$f" .md | tr '-' ' ')"

      # hook = 正文第一个非空行（跳过 frontmatter 与 # 标题行），去掉列表符号与 markdown 符号
      hook="$(awk '
        BEGIN { fm=0; done=0 }
        /^---$/ { if (fm==0) { fm=1; next } else { fm=0; next } }
        fm==1 || done==1 { next }
        /^#/ { next }
        NF>0 {
          gsub(/^[[:space:]]*[-*+>]*[[:space:]]*/, "");
          gsub(/\*\*/,""); gsub(/`/,"");
          while (match($0, /!\[[^]]*\]\([^)]*\)/)) $0 = substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH);
          while (match($0, /\[[^]]*\]\([^)]*\)/)) {
            link = substr($0, RSTART, RLENGTH);
            sub(/\]\([^)]*\)/, "]", link);
            gsub(/^\[|\]$/, "", link);
            $0 = substr($0,1,RSTART-1) link substr($0,RSTART+RLENGTH);
          }
          print; done=1
        }
      ' "$f")"
      [ -n "$hook" ] || hook="(无正文)"
      if [ "${#hook}" -gt 80 ]; then
        hook="${hook:0:77}…"
      fi

      printf -- "- [%s](%s) — %s\n" "$title" "$rel" "$hook"
    done < <(find "$dir" -maxdepth 1 -name '*.md' -type f ! -name '_template.md' ! -name 'README.md' | sort)
    echo
  done
} > "$TMP_FILE"

mv "$TMP_FILE" "$INDEX_FILE"
entries="$(grep -c '^- \[' "$INDEX_FILE" || true)"
echo "Index regenerated: $INDEX_FILE ($entries entries)"
