#!/usr/bin/env bash
# Matrixly Lead Qualifier — one-click install & sample demo (macOS / Linux)
# Double-click in Finder (Open With → Terminal) or run: ./install-and-demo.sh

set -u

info() { printf '  %s\n' "$*"; }
ok()   { printf '  %s\n' "$*"; }
err()  { printf '  %s\n' "$*" >&2; }

fail() {
  printf '\n' >&2
  err "$1"
  printf '\n' >&2
  info "Need a hand? Email anwar.chowdhury@matrixly.net"
  if [ -t 0 ]; then
    printf '\n  Press Enter to close...\n'
    read -r _
  fi
  exit "${2:-1}"
}

# Always run from this script's folder (agents/lead-qualifier), even from Finder.
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT" || fail "Could not open the Lead Qualifier folder."

OUT_FILE="$ROOT/demo-output.txt"
REQ_FILE="$ROOT/requirements.txt"
CLI_MARKER="$ROOT/src/cli.py"
VENV_DIR="$ROOT/.venv"

printf '\n'
printf '  Matrixly Lead Qualifier\n'
printf '  Install & sample demo — no terminal typing needed.\n'
printf '\n'

if [ ! -f "$REQ_FILE" ] || [ ! -f "$CLI_MARKER" ]; then
  fail "This installer must stay inside the Lead Qualifier folder.
  Please unzip the complete demo package first, then run this file from that folder."
}

find_system_python() {
  local cand ver
  for cand in python3 python; do
    if command -v "$cand" >/dev/null 2>&1; then
      ver="$("$cand" -c 'import sys; print("%d.%d" % sys.version_info[:2]); raise SystemExit(0 if sys.version_info >= (3, 10) else 2)' 2>/dev/null)" || continue
      if [ -n "$ver" ]; then
        printf '%s\n' "$cand"
        return 0
      fi
    fi
  done
  return 1
}

if [ "$(uname -s)" = "Darwin" ]; then
  VENV_PY="$VENV_DIR/bin/python3"
else
  VENV_PY="$VENV_DIR/bin/python"
fi
# Fall back if the venv used the other name.
if [ ! -x "$VENV_PY" ] && [ -x "$VENV_DIR/bin/python3" ]; then
  VENV_PY="$VENV_DIR/bin/python3"
fi
if [ ! -x "$VENV_PY" ] && [ -x "$VENV_DIR/bin/python" ]; then
  VENV_PY="$VENV_DIR/bin/python"
fi

if [ ! -x "$VENV_PY" ]; then
  SYS_PY="$(find_system_python || true)"
  if [ -z "${SYS_PY:-}" ]; then
    err "Python 3.10 or newer is needed for this demo (it's free)."
    printf '\n'
    info "1. Open  https://www.python.org/downloads/"
    info "2. Install Python 3.10 or newer"
    info "3. Run this file again"
    printf '\n'
    if [ -t 0 ]; then
      printf '  Press Enter to close...\n'
      read -r _
    fi
    exit 2
  fi

  info "Setting up a private folder for this demo (first time only)..."
  if ! "$SYS_PY" -m venv "$VENV_DIR"; then
    fail "Could not create the private demo folder. Please reinstall Python 3.10+ from python.org and try again."
  fi
  if [ -x "$VENV_DIR/bin/python3" ]; then
    VENV_PY="$VENV_DIR/bin/python3"
  else
    VENV_PY="$VENV_DIR/bin/python"
  fi
  if [ ! -x "$VENV_PY" ]; then
    fail "Could not create the private demo folder. Please reinstall Python 3.10+ from python.org and try again."
  fi
  ok "Private folder ready."
else
  info "Using the existing private folder (already installed)."
fi

# Activate when possible (also call venv python directly).
if [ -f "$VENV_DIR/bin/activate" ]; then
  # shellcheck disable=SC1091
  . "$VENV_DIR/bin/activate"
fi

info "Installing the demo (this can take 20–40 seconds the first time)..."
if ! "$VENV_PY" -m pip install --upgrade pip --disable-pip-version-check --progress-bar on >/dev/null 2>&1; then
  : # pip upgrade is optional
fi
if ! "$VENV_PY" -m pip install -r "$REQ_FILE" --disable-pip-version-check --progress-bar on; then
  fail "Could not install the demo files. Check your internet connection and try again."
fi
ok "Install complete."

printf '\n'
info "Scoring sample leads..."
printf '\n'

export PYTHONUNBUFFERED=1
export PYTHONIOENCODING=utf-8

RAW="$(mktemp "${TMPDIR:-/tmp}/lq-demo.XXXXXX")"
set +e
"$VENV_PY" -m src.cli sample --no-llm 2>&1 | tee "$RAW"
DEMO_EXIT="${PIPESTATUS[0]}"
# macOS / some shells: PIPESTATUS[0] is the first command. tee is [1].
if [ -z "${DEMO_EXIT:-}" ]; then
  DEMO_EXIT=0
fi
set -u

{
  printf 'Matrixly Lead Qualifier — sample demo\n'
  printf 'Saved: %s\n\n' "$(date '+%Y-%m-%d %H:%M')"
  "$VENV_PY" -c 'import re,sys; sys.stdout.write(re.sub(r"\x1B\[[0-9;]*[A-Za-z]","",sys.stdin.read()))' < "$RAW"
} > "$OUT_FILE" 2>/dev/null || cp "$RAW" "$OUT_FILE"
rm -f "$RAW"

printf '\n'
if [ "$DEMO_EXIT" -ne 0 ]; then
  err "The demo did not finish. Open demo-output.txt in this folder for details."
  info "Need a hand? Email anwar.chowdhury@matrixly.net"
  if [ -t 0 ]; then
    printf '\n  Press Enter to close...\n'
    read -r _
  fi
  exit 1
fi

ok "Demo finished. Open demo-output.txt to see the scored leads and sample outreach."
printf '\n'

# Keep the window open when launched from Finder / double-click.
if [ -t 0 ]; then
  if [ "${TERM_PROGRAM:-}" = "Apple_Terminal" ] || [ -n "${TERM_SESSION_ID:-}" ] || [ "${SHLVL:-1}" -le 2 ]; then
    printf '  Press Enter to close...\n'
    read -r _
  fi
fi

exit 0
