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

# ---------------------------------------------------------------------------
# Pyvorin Edge SDK — Raspberry Pi Benchmark Pack
# ---------------------------------------------------------------------------
# Self-contained script that runs the full 8-vertical benchmark suite on a
# Raspberry Pi and produces JSON + markdown artefacts.
#
# Usage: bash run-pi-benchmarks.sh
# ---------------------------------------------------------------------------

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 1. Verify we are inside a pyvorin-edge installation
VALID_ROOT=false
for candidate in /opt/pyvorin-edge /home/*/pyvorin-edge; do
    if [[ "$SCRIPT_DIR" == "$candidate"* ]] || [[ "$(pwd)" == "$candidate"* ]]; then
        VALID_ROOT=true
        break
    fi
done

if [[ "$VALID_ROOT" != "true" ]]; then
    echo "ERROR: This script must be run from inside /opt/pyvorin-edge or /home/*/pyvorin-edge" >&2
    echo "Current directory: $(pwd)" >&2
    exit 1
fi

# Resolve project root (script lives in pyvorin-edge/pifiles/)
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# 2. Activate venv
VENV_BIN=""
for vpath in "$PROJECT_ROOT/venv/bin" "$PROJECT_ROOT/.venv/bin"; do
    if [[ -f "$vpath/activate" ]]; then
        VENV_BIN="$vpath"
        break
    fi
done

if [[ -z "$VENV_BIN" ]]; then
    echo "ERROR: No virtual environment found in $PROJECT_ROOT/venv or $PROJECT_ROOT/.venv" >&2
    exit 1
fi

# shellcheck source=/dev/null
source "$VENV_BIN/activate"

echo "============================================================"
echo "Pyvorin Edge SDK — Raspberry Pi Benchmark Pack"
echo "Project root: $PROJECT_ROOT"
echo "Python: $(command -v python)"
echo "============================================================"

# 3. Run benchmarks
echo ""
echo "[1/3] Running 8-vertical benchmark suite ..."
cd "$PROJECT_ROOT"
python examples/industry_benchmarks/run_all.py

# 4. Generate case studies
echo ""
echo "[2/3] Generating case-study markdown ..."
python examples/industry_benchmarks/generate_case_studies.py

# 5. Copy artefacts to predictable paths
RESULTS_SRC="$PROJECT_ROOT/examples/industry_benchmarks/benchmark_results.json"
CASE_STUDIES_SRC="$PROJECT_ROOT/examples/industry_benchmarks/CASE_STUDIES.md"
OUT_DIR="$HOME/pyvorin-edge"
mkdir -p "$OUT_DIR"

cp "$RESULTS_SRC" "$OUT_DIR/benchmark_results_pi.json"
cp "$CASE_STUDIES_SRC" "$OUT_DIR/CASE_STUDIES_PI.md"

echo ""
echo "[3/3] Results saved to:"
echo "  - $OUT_DIR/benchmark_results_pi.json"
echo "  - $OUT_DIR/CASE_STUDIES_PI.md"

# 6. Print summary of all 8 verticals with £ savings
echo ""
echo "============================================================"
echo "                    BENCHMARK SUMMARY                       "
echo "============================================================"
printf "%-28s %10s %12s\n" "Vertical" "Reduction" "Savings (£)"
echo "------------------------------------------------------------"

python3 - <<'PY'
import json, sys
from pathlib import Path

p = Path.home() / "pyvorin-edge" / "benchmark_results_pi.json"
if not p.exists():
    sys.exit(0)

data = json.loads(p.read_text())
for r in data:
    v = r.get("vertical", "unknown")
    red = r.get("reduction_percent", 0.0)
    savings = r.get("cost_model", {}).get("cost_savings", 0.0)
    print(f"{v:28s} {red:>9.2f}%  £{savings:>10.2f}")
PY

echo "============================================================"
echo ""
echo "How to get the files off the Pi:"
echo ""
echo "  scp pi@<pi-ip>:~/pyvorin-edge/benchmark_results_pi.json ./"
echo "  scp pi@<pi-ip>:~/pyvorin-edge/CASE_STUDIES_PI.md ./"
echo ""
echo "  # Or with rsync:"
echo "  rsync -avz pi@<pi-ip>:~/pyvorin-edge/ ./pi-results/"
echo ""
echo "  # Or copy-paste the contents:"
echo "  cat ~/pyvorin-edge/benchmark_results_pi.json"
echo "  cat ~/pyvorin-edge/CASE_STUDIES_PI.md"
echo ""
