#!/usr/bin/env bash
# ---------------------------------------------------------------------------
# LuxiBook historical reproduction demo.
#
# Reproduces a valuation of real, executed option trades from a past date and
# checks it against a hash published in advance.
#
# Everything this script touches is free and public:
#   - the pricing binary comes from the public LuxiDemo repo
#   - the market data comes from Deribit's public history API (no key, no account)
# No paid data vendor, no NDA, no credentials.
#
# Usage:   bash reproduce.sh            # runs both pinned dates
#          bash reproduce.sh 2025-02-18 # runs one
# ---------------------------------------------------------------------------
set -u

RAW="https://raw.githubusercontent.com/RegularJoe-CEO/LuxiDemo/main/downloads/luxibook"
BIN="luxi-book-linux-x86_64"
BIN_SHA="b4c14b9e0ceddf86e7a518d36d9ea48e5d6b07c72c331294a90af2100cc53c29"

# Pinned acceptance values. These were published BEFORE you ran this script.
# date | input_sha256 | output_vector_sha256 | book_price | row_count
PINS="
2025-02-18|7ffb96d4668d7ca795d87888bf99884d0e23653a0bb7ddf6e466d02c2170b39e|f52c7f15812490617009efd09d7703414d80fc1badc3fb8d88c386b56fc8155c|33842393.3392818272|11317
2024-11-05|277b4c8b41ab04f816d60c7ffa81142f9f2c6864f7aeb6b8dbc3194d3e52fafa|be78fd221673213eec90477e01260804492bb2e74dd37b163bc9aef1d97a2a48|60831980.0959759504|14879
"

FAILURES=0
say() { printf '%s\n' "$*"; }
hr()  { printf '%s\n' "-----------------------------------------------------------"; }

# --- step 1: get the published binary and prove it is the published one ------
hr; say "STEP 1  Fetch the published binary and check its checksum"
if [ ! -f "$BIN" ]; then
  curl -fsSL -o "$BIN" "$RAW/$BIN" || { say "FAIL: download"; exit 1; }
fi
GOT=$(sha256sum "$BIN" | cut -d' ' -f1)
say "  expected $BIN_SHA"
say "  got      $GOT"
if [ "$GOT" != "$BIN_SHA" ]; then
  say "  FAIL: this is not the published binary. Stopping."
  exit 1
fi
say "  OK: byte-identical to the published release."
chmod +x "$BIN"

export LUXIQUANT_HOME="${LUXIQUANT_HOME:-$PWD/.luxiquant}"
mkdir -p "$LUXIQUANT_HOME"

DATES="${1:-}"
if [ -z "$DATES" ]; then DATES="2025-02-18 2024-11-05"; fi

for DATE in $DATES; do
  LINE=$(printf '%s\n' "$PINS" | grep "^$DATE|") || true
  if [ -z "$LINE" ]; then say "no pin for $DATE, skipping"; continue; fi
  P_IN=$(echo "$LINE"  | cut -d'|' -f2)
  P_OUT=$(echo "$LINE" | cut -d'|' -f3)
  P_PX=$(echo "$LINE"  | cut -d'|' -f4)
  P_ROWS=$(echo "$LINE"| cut -d'|' -f5)

  hr; say "STEP 2  Rebuild the book for $DATE from Deribit's public history"
  python3 build_historical_book.py "$DATE" > "r_book_$DATE.csv" 2>/dev/null
  IN=$(sha256sum "r_book_$DATE.csv" | cut -d' ' -f1)
  say "  rows      $(grep -vc '^#' "r_book_$DATE.csv" | awk '{print $1-1}')  (expected $P_ROWS)"
  say "  expected  $P_IN"
  say "  got       $IN"
  if [ "$IN" = "$P_IN" ]; then
    say "  OK: the reconstructed book is byte-identical to the sealed one."
  else
    say "  DIFFERENT. The venue returned different bytes than when this was sealed."
    say "  That is itself the useful signal: the input changed, so the valuation"
    say "  is not the same valuation. Continuing so you can see the seal react."
    FAILURES=$((FAILURES+1))
  fi

  hr; say "STEP 3  Price and seal it"
  ./"$BIN" price --book "r_book_$DATE.csv" --out "r_priced_$DATE.csv" \
      --receipt "r_receipt_$DATE.json" | sed 's/^/  /'

  hr; say "STEP 4  Check against the values published in advance"
  GOT_OUT=$(python3 -c "import json;print(json.load(open('r_receipt_$DATE.json'))['output_vector_sha256'])")
  GOT_PX=$(grep -oE 'book_price:[[:space:]]+[-0-9.]+' /dev/null 2>/dev/null || true)
  GOT_PX=$(python3 -c "
import csv
for r in open('r_priced_$DATE.csv'):
    f=r.split(',')
    if f[0]=='TOTAL': print('%.10f'%float(f[4])); break
")
  say "  output_vector_sha256 expected $P_OUT"
  say "  output_vector_sha256 got      $GOT_OUT"
  [ "$GOT_OUT" = "$P_OUT" ] && say "  OK" || { say "  MISMATCH"; FAILURES=$((FAILURES+1)); }
  say "  book_price expected ~$P_PX"
  say "  book_price got       $GOT_PX"

  hr; say "STEP 5  Verify the seal"
  ./"$BIN" verify --book "r_book_$DATE.csv" --receipt "r_receipt_$DATE.json" | sed 's/^/  /'
  RC=${PIPESTATUS[0]}
  say "  verify exit code $RC  (0 = pass)"
  [ "$RC" -eq 0 ] || FAILURES=$((FAILURES+1))
done

# --- the part that matters: make it fail on purpose --------------------------
D=$(echo $DATES | awk '{print $1}')
hr; say "STEP 6  Now break it on purpose"
say "  Changing ONE implied vol, in the 15th significant digit, in ONE row."
python3 - "$D" <<'PY'
import sys
d=sys.argv[1]
lines=open("r_book_%s.csv"%d).read().split("\n")
h=[i for i,l in enumerate(lines) if l.startswith("id,")][0]
i=min(h+5000,len(lines)-2)
f=lines[i].split(",")
old=f[5]; f[5]="%.17g"%(float(old)*(1+1e-15))
print("  row       %s"%f[0]); print("  sigma old %s"%old); print("  sigma new %s"%f[5])
lines[i]=",".join(f)
open("r_book_tampered.csv","w").write("\n".join(lines))
PY
say ""
say "  Verifying the altered book against the ORIGINAL receipt:"
./"$BIN" verify --book r_book_tampered.csv --receipt "r_receipt_$D.json" | sed 's/^/  /'
RC=${PIPESTATUS[0]}
say "  verify exit code $RC  (expected 1)"
[ "$RC" -eq 1 ] || { say "  UNEXPECTED: the tamper was not caught."; FAILURES=$((FAILURES+1)); }

hr
if [ "$FAILURES" -eq 0 ]; then
  say "ALL CHECKS BEHAVED AS PUBLISHED."
else
  say "$FAILURES check(s) did not match. Read the output above."
fi
say ""
say "What this did and did not show."
say "  It showed: the same input bytes give the same output numbers and the same"
say "  hash, on this machine, from a binary you checksummed yourself, on real"
say "  trades that printed on a public venue on a past date. And it showed the"
say "  seal reacting to a change far too small to see in a P&L report."
say "  It did not show: that the prices are the RIGHT prices. A hash cannot say"
say "  that. It says the numbers did not change."
hr
exit 0

