#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

ARTIFACTS_DIR="${ARTIFACTS_DIR:-$ROOT_DIR/artifacts}"
SEED="${SEED:-42}"
ITERATIONS="${ITERATIONS:-2000}"

mkdir -p "$ARTIFACTS_DIR"

TIMESTAMP_UTC="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
DATE_UTC="$(date -u +"%Y-%m-%d")"
COMMIT_SHA="$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")"
UNAME_STR="$(uname -a | tr '"' "'")"
RUSTC_VER="$(rustc --version 2>/dev/null || echo "unknown")"
CARGO_VER="$(cargo --version 2>/dev/null || echo "unknown")"

BENCH_JSON="$ARTIFACTS_DIR/acceptance_bench_result.json"
REPORT_JSON="$ARTIFACTS_DIR/acceptance_gate_report.json"
REPORT_MD="$ARTIFACTS_DIR/acceptance_gate_report.md"
CONTRACT_JSON="$ARTIFACTS_DIR/acceptance_alloy_contract.json"

LOG_TEST_WORKSPACE="$ARTIFACTS_DIR/acceptance_cmd_test_workspace.log"
LOG_TEST_INTEGRATION="$ARTIFACTS_DIR/acceptance_cmd_test_integration.log"
LOG_TEST_PLEXUS="$ARTIFACTS_DIR/acceptance_cmd_test_plexus_restart.log"
LOG_BENCH="$ARTIFACTS_DIR/acceptance_cmd_bench.log"

run_and_log() {
  local log_file="$1"
  shift
  set +e
  "$@" >"$log_file" 2>&1
  local status=$?
  set -e
  echo "$status"
}

echo "Running acceptance commands..."
STATUS_TEST_WORKSPACE="$(run_and_log "$LOG_TEST_WORKSPACE" cargo test --workspace)"
STATUS_TEST_INTEGRATION="$(run_and_log "$LOG_TEST_INTEGRATION" cargo test --release --test storage_paths)"
STATUS_TEST_PLEXUS="$(run_and_log "$LOG_TEST_PLEXUS" cargo test --release --test storage_paths integration_embedded_driver_plexus_restart_round_trip -- --exact)"
STATUS_BENCH="$(run_and_log "$LOG_BENCH" cargo run --release --bin ir -- bench "$ITERATIONS" --seed "$SEED" --json "$BENCH_JSON")"
cargo run --quiet --bin ir -- contract-report acceptance >"$CONTRACT_JSON"

extract_json_number() {
  local key="$1"
  local file="$2"
  grep -E "\"$key\"[[:space:]]*:" "$file" | head -n1 | sed -E 's/.*: ([^,}]+).*/\1/'
}

INGEST_EDGES_PER_SEC="0"
TRAVERSAL_P99_US="0"
WRITE_AMP="null"

if [[ -f "$BENCH_JSON" ]]; then
  INGEST_EDGES_PER_SEC="$(extract_json_number "edges_per_sec" "$BENCH_JSON" || echo "0")"
  TRAVERSAL_P99_US="$(extract_json_number "p99_micros" "$BENCH_JSON" || echo "0")"
  WRITE_AMP="$(extract_json_number "write_amp" "$BENCH_JSON" || echo "null")"
fi

PASS_INGEST="false"
PASS_TRAVERSAL="false"
PASS_WRITE_AMP="false"
PASS_PATH_COVERAGE="false"

if awk "BEGIN {exit !($INGEST_EDGES_PER_SEC >= 1000000)}"; then PASS_INGEST="true"; fi
if awk "BEGIN {exit !($TRAVERSAL_P99_US < 100)}"; then PASS_TRAVERSAL="true"; fi
if [[ "$WRITE_AMP" != "null" ]] && awk "BEGIN {exit !($WRITE_AMP < 4.0)}"; then PASS_WRITE_AMP="true"; fi
if [[ "$STATUS_TEST_WORKSPACE" -eq 0 && "$STATUS_TEST_INTEGRATION" -eq 0 && "$STATUS_TEST_PLEXUS" -eq 0 ]]; then PASS_PATH_COVERAGE="true"; fi

OVERALL_PASS="false"
if [[ "$PASS_INGEST" == "true" && "$PASS_TRAVERSAL" == "true" && "$PASS_WRITE_AMP" == "true" && "$PASS_PATH_COVERAGE" == "true" ]]; then
  OVERALL_PASS="true"
fi

cat >"$REPORT_JSON" <<EOF
{
  "timestamp_utc": "$TIMESTAMP_UTC",
  "date_utc": "$DATE_UTC",
  "commit_sha": "$COMMIT_SHA",
  "seed": $SEED,
  "iterations": $ITERATIONS,
  "machine": {
    "uname": "$UNAME_STR",
    "rustc": "$RUSTC_VER",
    "cargo": "$CARGO_VER"
  },
  "commands": {
    "cargo_test_workspace": {
      "command": "cargo test --workspace",
      "status": $STATUS_TEST_WORKSPACE,
      "log": "$(basename "$LOG_TEST_WORKSPACE")"
    },
    "cargo_test_release_integration": {
      "command": "cargo test --release --test storage_paths",
      "status": $STATUS_TEST_INTEGRATION,
      "log": "$(basename "$LOG_TEST_INTEGRATION")"
    },
    "cargo_test_release_plexus_restart": {
      "command": "cargo test --release --test storage_paths integration_embedded_driver_plexus_restart_round_trip -- --exact",
      "status": $STATUS_TEST_PLEXUS,
      "log": "$(basename "$LOG_TEST_PLEXUS")"
    },
    "cargo_run_release_bench": {
      "command": "cargo run --release --bin ir -- bench $ITERATIONS --seed $SEED --json $BENCH_JSON",
      "status": $STATUS_BENCH,
      "log": "$(basename "$LOG_BENCH")"
    }
  },
  "metrics": {
    "ingest_edges_per_sec": $INGEST_EDGES_PER_SEC,
    "traversal_p99_micros": $TRAVERSAL_P99_US,
    "write_amp": $WRITE_AMP
  },
  "alloy_contract_path": "$(basename "$CONTRACT_JSON")",
  "criteria": {
    "ingest_edges_per_sec_gte_1m": $PASS_INGEST,
    "traversal_10hop_p99_lt_100us": $PASS_TRAVERSAL,
    "write_amp_lt_4x": $PASS_WRITE_AMP,
    "all_paths_exercised_via_integration_tests": $PASS_PATH_COVERAGE
  },
  "overall_pass": $OVERALL_PASS
}
EOF

cat >"$REPORT_MD" <<EOF
# Acceptance Report

- Timestamp (UTC): $TIMESTAMP_UTC
- Commit: $COMMIT_SHA
- Seed: $SEED
- Iterations: $ITERATIONS

## Machine
- \`uname\`: $UNAME_STR
- \`rustc\`: $RUSTC_VER
- \`cargo\`: $CARGO_VER

## Command Results
1. \`cargo test --workspace\` -> status: $STATUS_TEST_WORKSPACE (log: $(basename "$LOG_TEST_WORKSPACE"))
2. \`cargo test --release --test storage_paths\` -> status: $STATUS_TEST_INTEGRATION (log: $(basename "$LOG_TEST_INTEGRATION"))
3. \`cargo test --release --test storage_paths integration_embedded_driver_plexus_restart_round_trip -- --exact\` -> status: $STATUS_TEST_PLEXUS (log: $(basename "$LOG_TEST_PLEXUS"))
4. \`cargo run --release --bin ir -- bench $ITERATIONS --seed $SEED --json $BENCH_JSON\` -> status: $STATUS_BENCH (log: $(basename "$LOG_BENCH"))

## Metrics
- ingest edges/sec: $INGEST_EDGES_PER_SEC
- traversal p99 (microseconds): $TRAVERSAL_P99_US
- write amplification: $WRITE_AMP
- shared alloy contract: $(basename "$CONTRACT_JSON")

## Criteria
- Ingest >= 1,000,000 edges/sec: $PASS_INGEST
- Traversal p99 < 100 microseconds: $PASS_TRAVERSAL
- Write amplification < 4x: $PASS_WRITE_AMP
- All paths exercised via integration tests: $PASS_PATH_COVERAGE

## Overall
- overall_pass: $OVERALL_PASS
EOF

echo "Wrote:"
echo "  $REPORT_JSON"
echo "  $REPORT_MD"
