#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SOURCE_DIR="${ROOT_DIR}/Sources/CodexBarCore/Vendored/CostUsage"
OUTPUT_FILE="${ROOT_DIR}/Sources/CodexBarCore/Generated/CodexParserHash.generated.swift"
MODE="${1:-write}"

case "$MODE" in
  write | --write)
    CHECK_ONLY=0
    ;;
  check | --check)
    CHECK_ONLY=1
    ;;
  *)
    echo "Usage: $0 [write|--write|check|--check]" >&2
    exit 2
    ;;
esac

if command -v shasum >/dev/null 2>&1; then
  HASH_CMD=(shasum -a 256)
elif command -v sha256sum >/dev/null 2>&1; then
  HASH_CMD=(sha256sum)
else
  echo "error: shasum or sha256sum is required" >&2
  exit 1
fi

FILE_LIST="$(mktemp)"
trap 'rm -f "$FILE_LIST"' EXIT

# Storage-only files have their own schema-version gate and do not change parser semantics.
find "$SOURCE_DIR" \
  -type f \
  -name '*.swift' \
  ! -name '*Claude*' \
  ! -name 'CostUsageStore*.swift' \
  -print |
  sed "s#^${ROOT_DIR}/##" |
  LC_ALL=C sort >"$FILE_LIST"

HASH="$(
  while IFS= read -r file; do
    printf '== %s ==\n' "$file"
    cat "${ROOT_DIR}/${file}"
    printf '\n'
  done <"$FILE_LIST" | "${HASH_CMD[@]}"
)"
HASH="${HASH%% *}"
SHORT_HASH="${HASH:0:16}"

render_generated() {
  cat <<SWIFT
// Generated by Scripts/regenerate-codex-parser-hash.sh. Do not edit by hand.

enum CodexParserHash {
    static let value = "$SHORT_HASH"
}
SWIFT
}

if [[ "$CHECK_ONLY" -eq 1 ]]; then
  EXPECTED_FILE="$(mktemp)"
  trap 'rm -f "$FILE_LIST" "$EXPECTED_FILE"' EXIT
  render_generated >"$EXPECTED_FILE"
  if ! cmp -s "$EXPECTED_FILE" "$OUTPUT_FILE"; then
    echo "error: ${OUTPUT_FILE#${ROOT_DIR}/} is stale. Run Scripts/regenerate-codex-parser-hash.sh and commit the result." >&2
    if [[ -f "$OUTPUT_FILE" ]]; then
      diff -u "$OUTPUT_FILE" "$EXPECTED_FILE" >&2 || true
    else
      diff -u /dev/null "$EXPECTED_FILE" >&2 || true
    fi
    exit 1
  fi
  echo "Codex parser hash is current (${SHORT_HASH})"
  exit 0
fi

mkdir -p "$(dirname "$OUTPUT_FILE")"
render_generated >"$OUTPUT_FILE"

echo "Updated ${OUTPUT_FILE#${ROOT_DIR}/} to ${SHORT_HASH}"
