#!/usr/bin/env bash
# Extract ProfTools_VendorDump + ProfTools_CatalogSchema from the live ProfTools
# SavedVariables into HDG's dev_data reference snapshots.
#
# These snapshots are NOT auto-synced -- regenerate them by hand:
#   1. In-game: ProfTools -> Vendor Browser -> "Refresh" (populates the vendor index)
#   2.          -> "Dump to SV"   (writes ProfTools_VendorDump)
#              -> "Dump Schema"   (writes ProfTools_CatalogSchema)
#   3. /reload  (flushes SavedVariables to disk -- in-memory until then)
#   4. Run this script.
#
# Usage: ./extract_pt_dumps.sh [path-to-ProfTools.lua]
set -euo pipefail

SV="${1:-/Applications/World of Warcraft/_retail_/WTF/Account/JUSTINLEDWARDS/SavedVariables/ProfTools.lua}"
DEST="$(cd "$(dirname "$0")" && pwd)"

[ -f "$SV" ] || { echo "SavedVariables not found: $SV" >&2; exit 1; }

# Slice one top-level global block ("NAME = { ... }") out of the SavedVariables.
# Top-level globals are the only lines matching ^ProfTools_<Name> = , so we
# capture from our global's decl up to (but not including) the next global decl.
extract() {  # $1 = global name, $2 = output file
    local tmp; tmp="$(mktemp)"
    awk -v G="$1" '
        /^ProfTools_[A-Za-z]+ = / {
            if ($0 ~ ("^" G " = ")) { p = 1; print; next }
            else if (p) { exit }
        }
        p { print }
    ' "$SV" > "$tmp"
    if [ "$(head -1 "$tmp" | tr -d '\r')" = "$1 = {" ]; then   # snapshots are CRLF; strip CR for the guard only
        mv "$tmp" "$2"
        echo "OK   $1 -> $(basename "$2")  ($(wc -l < "$2" | tr -d ' ') lines, $(wc -c < "$2" | tr -d ' ') bytes)"
    else
        rm -f "$tmp"
        echo "SKIP $1 -- not populated in SavedVariables (run the in-game dump + /reload first)" >&2
    fi
}

extract ProfTools_VendorDump   "$DEST/ProfTools_VendorDump.lua"
extract ProfTools_CatalogSchema "$DEST/ProfTools_CatalogSchema.lua"
