#!/bin/bash

# Run Go benchmark and save results
echo "=== Go jdenticon Performance Benchmark ==="
echo "Running Go benchmark..."

# Run the benchmark and capture output
BENCHMARK_OUTPUT=$(cd .. && go test -run="^$" -bench=BenchmarkGenerate64pxIcon -benchmem ./jdenticon 2>&1)

echo "$BENCHMARK_OUTPUT"

# Parse benchmark results
# Example output: BenchmarkGenerate64pxIcon-10    	   92173	     12492 ns/op	   13174 B/op	     239 allocs/op
BENCHMARK_LINE=$(echo "$BENCHMARK_OUTPUT" | grep BenchmarkGenerate64pxIcon)
ITERATIONS=$(echo "$BENCHMARK_LINE" | awk '{print $2}')
NS_PER_OP=$(echo "$BENCHMARK_LINE" | awk '{print $3}')
BYTES_PER_OP=$(echo "$BENCHMARK_LINE" | awk '{print $5}')
ALLOCS_PER_OP=$(echo "$BENCHMARK_LINE" | awk '{print $7}')

# Convert nanoseconds to milliseconds and microseconds  
TIME_PER_ICON_MS=$(echo "scale=4; $NS_PER_OP / 1000000" | bc | awk '{printf "%.4f", $0}')
TIME_PER_ICON_US=$(echo "scale=2; $NS_PER_OP / 1000" | bc | awk '{printf "%.2f", $0}')
ICONS_PER_SECOND=$(echo "scale=2; 1000000000 / $NS_PER_OP" | bc)

echo ""
echo "=== go-jdenticon Results ==="
echo "Iterations: $ITERATIONS"
echo "Time per icon: ${TIME_PER_ICON_MS} ms (${TIME_PER_ICON_US} μs)"
echo "Throughput: ${ICONS_PER_SECOND} icons/sec"
echo "Memory per icon: $BYTES_PER_OP bytes"
echo "Allocations per icon: $ALLOCS_PER_OP allocs"

# Create JSON results
cat > results-go.json << EOF
{
  "implementation": "go-jdenticon",
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")",
  "goVersion": "$(go version | awk '{print $3}')",
  "config": {
    "iconSize": 64,
    "numInputs": 1000,
    "benchmarkIterations": $ITERATIONS
  },
  "performance": {
    "nsPerOp": $NS_PER_OP,
    "timePerIconMs": $TIME_PER_ICON_MS,
    "timePerIconUs": $TIME_PER_ICON_US,
    "iconsPerSecond": $ICONS_PER_SECOND
  },
  "memory": {
    "bytesPerOp": $(echo "$BYTES_PER_OP" | sed 's/[^0-9]//g'),
    "allocsPerOp": $(echo "$ALLOCS_PER_OP" | sed 's/[^0-9]//g')
  }
}
EOF

echo ""
echo "Results saved to: results-go.json"