#!/usr/bin/env bash
# measure.sh — XDPoS parity score
# Runs all checks under checks/, sums points, prints JSON breakdown.
# Fast (<10s); pure grep/file checks. For correctness gate, see validate.sh.

set -uo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PATIENT="${PATIENT:-/Users/anilchinchawale/github/XDCNetwork/XDC-Geth}"
REFERENCE="${REFERENCE:-/Users/anilchinchawale/github/XDCNetwork/XDPoSChain}"

if [[ ! -d "$PATIENT" ]]; then
  echo "ERROR: PATIENT directory not found: $PATIENT" >&2
  exit 1
fi
if [[ ! -d "$REFERENCE" ]]; then
  echo "ERROR: REFERENCE directory not found: $REFERENCE" >&2
  exit 1
fi

export PATIENT REFERENCE

declare -a results=()
total=0
max=0
fail_count=0
pass_count=0

# Run checks in numeric order.
for check in "$HERE"/checks/[0-9][0-9]_*.sh; do
  [[ -f "$check" ]] || continue
  name="$(basename "$check" .sh)"
  weight="$(grep -m1 '^# WEIGHT=' "$check" | cut -d= -f2 | tr -d ' ')"
  [[ -z "${weight:-}" ]] && weight=1
  max=$((max + weight))

  if bash "$check" >/dev/null 2>&1; then
    points=$weight
    status="pass"
    pass_count=$((pass_count + 1))
  else
    points=0
    status="fail"
    fail_count=$((fail_count + 1))
  fi
  total=$((total + points))
  results+=("    {\"name\":\"$name\",\"weight\":$weight,\"points\":$points,\"status\":\"$status\"}")
done

# Pretty JSON output.
echo "{"
echo "  \"score\": $total,"
echo "  \"max\": $max,"
echo "  \"percent\": $(awk "BEGIN { printf \"%.1f\", $total*100/$max }"),"
echo "  \"pass\": $pass_count,"
echo "  \"fail\": $fail_count,"
echo "  \"checks\": ["
printf "%s,\n" "${results[@]}" | sed '$s/,$//'
echo "  ]"
echo "}"
