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

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

VENV="${VENV:-$ROOT/.venv}"
PYTHON="$VENV/bin/python"
FIVETRAN="$VENV/bin/fivetran"
CONFIG="$ROOT/examples/local_debug_configuration.json"
EXPECTED="$ROOT/examples/local_debug_expected.json"
INPUT_SQL=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --input-sql)
      INPUT_SQL="${2:-}"
      if [[ -z "$INPUT_SQL" ]]; then
        echo "--input-sql requires a path"
        exit 2
      fi
      shift 2
      ;;
    -h|--help)
      echo "Usage: scripts/local_debug_run.sh [--input-sql /path/to/fivetran-test.sql]"
      exit 0
      ;;
    *)
      echo "Unknown argument: $1"
      exit 2
      ;;
  esac
done

if [[ ! -x "$PYTHON" || ! -x "$FIVETRAN" ]]; then
  echo "Missing .venv or fivetran CLI. Create it with:"
  echo "  python3 -m venv .venv"
  echo "  UV_CACHE_DIR=.uv-cache uv pip install --python .venv/bin/python -e . pytest"
  exit 2
fi

export PATH="$VENV/bin:$PATH"

if ! "$PYTHON" -c "import duckdb" >/dev/null 2>&1; then
  if command -v uv >/dev/null 2>&1; then
    UV_CACHE_DIR="${UV_CACHE_DIR:-$ROOT/.uv-cache}" uv pip install --python "$PYTHON" duckdb
  elif "$PYTHON" -m pip --version >/dev/null 2>&1; then
    "$PYTHON" -m pip install duckdb
  else
    echo "duckdb is missing, and neither uv nor pip is available. Install duckdb in $VENV manually."
    exit 2
  fi
fi

prepare_args=()
verify_args=()
if [[ -n "$INPUT_SQL" ]]; then
  if [[ ! -r "$INPUT_SQL" ]]; then
    echo "Input SQL is not readable: $INPUT_SQL"
    echo "If it is under /root, copy it to a readable path or run this script as a user that can read it."
    exit 2
  fi
  prepare_args+=(--input-sql "$INPUT_SQL" --expected "$EXPECTED")
  verify_args+=(--expected "$EXPECTED")
fi

"$PYTHON" scripts/local_debug_prepare.py phase1 --reset-debug-output "${prepare_args[@]}"
"$FIVETRAN" debug . --configuration "$CONFIG"
"$PYTHON" scripts/local_debug_verify_duckdb.py phase1 "${verify_args[@]}"

if [[ -n "$INPUT_SQL" ]]; then
  has_phase2="$("$PYTHON" - "$EXPECTED" <<'PY'
import json
import sys
from pathlib import Path

path = Path(sys.argv[1])
payload = json.loads(path.read_text(encoding="utf-8"))
print("yes" if "phase2" in payload else "no")
PY
)"
  if [[ "$has_phase2" != "yes" ]]; then
    echo "No phase2 marker found in SQL; completed phase1 snapshot/incremental debug."
    exit 0
  fi
fi

"$PYTHON" scripts/local_debug_prepare.py phase2 "${prepare_args[@]}"
"$FIVETRAN" debug . --configuration "$CONFIG"
"$PYTHON" scripts/local_debug_verify_duckdb.py phase2 "${verify_args[@]}"
