#!/usr/bin/env bash
# Generate docs/adr/index.toml + docs/adr/index.json from ADR YAML frontmatter.
# Usage: scripts/adr/generate-index.sh
#
# Uses only portable awk/sed/grep -- no Python, no Ruby, no jq.
# Parses the YAML frontmatter block between --- markers.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
ADR_DIR="$REPO_ROOT/docs/adr"
INDEX_TOML="$ADR_DIR/index.toml"
INDEX_JSON="$ADR_DIR/index.json"

# --- Helper: escape for JSON string interpolation ---
json_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

# --- Helper: extract a scalar field from frontmatter ---
# Usage: extract_scalar "field_name" "$frontmatter"
extract_scalar() {
  local field="$1" fm="$2"
  printf '%s\n' "$fm" | grep -E "^${field}:" | head -1 \
    | sed -E "s/^${field}:[[:space:]]*//" \
    | sed -E 's/^"//; s/"$//' \
    | sed -E "s/^'//; s/'$//"
}

# --- Helper: extract an inline array field from frontmatter ---
# Usage: extract_array "field_name" "$frontmatter"
# Returns one element per line, stripped of quotes and brackets.
extract_array() {
  local field="$1" fm="$2"
  printf '%s\n' "$fm" | grep -E "^${field}:" | head -1 \
    | sed -E "s/^${field}:[[:space:]]*//" \
    | tr -d '[]' \
    | tr ',' '\n' \
    | sed -E 's/^[[:space:]]*//; s/[[:space:]]*$//' \
    | sed -E 's/^"//; s/"$//' \
    | sed -E "s/^'//; s/'$//" \
    | { grep -v '^$' || true; }
}

# --- Helper: format array as JSON array ---
# Reads lines from stdin, outputs ["a","b","c"]
to_json_array() {
  local first=1 result="["
  while IFS= read -r item; do
    [ -z "$item" ] && continue
    [ $first -eq 0 ] && result="${result},"
    first=0
    item="$(json_escape "$item")"
    result="${result}\"${item}\""
  done
  result="${result}]"
  printf '%s' "$result"
}

# --- Helper: format array as TOML inline array ---
to_toml_array() {
  local first=1 result="["
  while IFS= read -r item; do
    [ -z "$item" ] && continue
    [ $first -eq 0 ] && result="${result}, "
    first=0
    result="${result}\"${item}\""
  done
  result="${result}]"
  printf '%s' "$result"
}

# --- Collect ADR files ---
adr_files=()
for f in "$ADR_DIR"/adr-[0-9][0-9][0-9]-*.md; do
  [ -f "$f" ] || continue
  adr_files+=("$f")
done

if [ ${#adr_files[@]} -eq 0 ]; then
  echo "ERROR: no ADR files found in $ADR_DIR" >&2
  exit 2
fi

# --- Generate index.toml ---
{
  echo "# ADR Index -- auto-generated by scripts/adr/generate-index.sh"
  echo "# Do not edit manually. Re-generate with: scripts/adr/generate-index.sh"
  echo "schema_version = \"v1\""
  echo "count = ${#adr_files[@]}"
  echo ""

  for filepath in "${adr_files[@]}"; do
    fname="$(basename "$filepath")"
    # Extract frontmatter (between first --- and second ---)
    frontmatter="$(awk '/^---$/{n++; next} n==1{print} n>=2{exit}' "$filepath")"
    if [ -z "$frontmatter" ]; then
      echo "# WARN: $fname has no YAML frontmatter, skipping" >&2
      continue
    fi

    adr_id="$(extract_scalar "id" "$frontmatter")"
    title="$(extract_scalar "title" "$frontmatter")"
    status="$(extract_scalar "status" "$frontmatter")"
    date="$(extract_scalar "date" "$frontmatter")"

    echo "[[adr]]"
    echo "id = \"${adr_id}\""
    echo "title = \"${title}\""
    echo "status = \"${status}\""
    echo "date = \"${date}\""
    echo "filename = \"${fname}\""

    tags="$(extract_array "tags" "$frontmatter" | to_toml_array)"
    [ "$tags" != "[]" ] && echo "tags = ${tags}"

    crates="$(extract_array "affects_crates" "$frontmatter" | to_toml_array)"
    [ "$crates" != "[]" ] && echo "affects_crates = ${crates}"

    layers="$(extract_array "affects_layers" "$frontmatter" | to_toml_array)"
    [ "$layers" != "[]" ] && echo "affects_layers = ${layers}"

    echo ""
  done
} >"$INDEX_TOML"

echo "Generated $INDEX_TOML (${#adr_files[@]} ADRs)"

# --- Generate index.json ---
{
  echo "{"
  echo "  \"schema_version\": \"v1\","
  echo "  \"generated\": true,"
  echo "  \"adrs\": ["

  first_adr=1
  for filepath in "${adr_files[@]}"; do
    fname="$(basename "$filepath")"
    frontmatter="$(awk '/^---$/{n++; next} n==1{print} n>=2{exit}' "$filepath")"
    [ -z "$frontmatter" ] && continue

    adr_id="$(json_escape "$(extract_scalar "id" "$frontmatter")")"
    title="$(json_escape "$(extract_scalar "title" "$frontmatter")")"
    status="$(json_escape "$(extract_scalar "status" "$frontmatter")")"
    date="$(json_escape "$(extract_scalar "date" "$frontmatter")")"

    tags_json="$(extract_array "tags" "$frontmatter" | to_json_array)"
    crates_json="$(extract_array "affects_crates" "$frontmatter" | to_json_array)"
    layers_json="$(extract_array "affects_layers" "$frontmatter" | to_json_array)"
    supersedes_json="$(extract_array "supersedes" "$frontmatter" | to_json_array)"
    superseded_by_json="$(extract_array "superseded_by" "$frontmatter" | to_json_array)"
    related_json="$(extract_array "related" "$frontmatter" | to_json_array)"
    requires_json="$(extract_array "requires" "$frontmatter" | to_json_array)"
    enables_json="$(extract_array "enables" "$frontmatter" | to_json_array)"

    [ $first_adr -eq 0 ] && echo "    ,"
    first_adr=0

    cat <<ENTRY
    {
      "id": "${adr_id}",
      "title": "${title}",
      "status": "${status}",
      "date": "${date}",
      "filename": "$(json_escape "$fname")",
      "tags": ${tags_json},
      "affects_crates": ${crates_json},
      "affects_layers": ${layers_json},
      "supersedes": ${supersedes_json},
      "superseded_by": ${superseded_by_json},
      "related": ${related_json},
      "requires": ${requires_json},
      "enables": ${enables_json}
    }
ENTRY
  done

  echo "  ]"
  echo "}"
} >"$INDEX_JSON"

echo "Generated $INDEX_JSON (${#adr_files[@]} ADRs)"
