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

cd "$(dirname "$0")/.."

GREEN="\033[0;32m"
YELLOW="\033[1;33m"
RED="\033[0;31m"
BLUE="\033[0;34m"
NC="\033[0m"

ok() {
  printf "${GREEN}[OK]${NC} %s\n" "$1"
}

warn() {
  printf "${YELLOW}[WARN]${NC} %s\n" "$1"
}

fail() {
  printf "${RED}[FAIL]${NC} %s\n" "$1"
}

info() {
  printf "${BLUE}[INFO]${NC} %s\n" "$1"
}

HAS_FAIL=0
HAS_WARN=0

require_file() {
  local f="$1"
  if [ -f "$f" ]; then
    ok "Found file: $f"
  else
    fail "Missing required file: $f"
    HAS_FAIL=1
  fi
}

require_cmd() {
  local c="$1"
  if command -v "$c" >/dev/null 2>&1; then
    ok "Command available: $c"
  else
    fail "Missing command: $c"
    HAS_FAIL=1
  fi
}

PY_BIN="python3"
if [ -f ".venv/bin/python" ]; then
  PY_BIN=".venv/bin/python"
  info "Using virtualenv Python: $PY_BIN"
else
  info "Using system Python (no .venv found)"
fi

require_file "Main.py"
require_file "requirements.txt"
require_file "requirements-optional.txt"
require_file "server/app.py"
require_cmd "$PY_BIN"

PY_VER="$("$PY_BIN" -c 'import sys; print(".".join(map(str, sys.version_info[:3])))')"
MAJOR_MINOR="$("$PY_BIN" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")')"
info "Python version: $PY_VER"
if "$PY_BIN" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)'; then
  ok "Python version is >= 3.11"
else
  fail "Python must be >= 3.11 (found $MAJOR_MINOR)"
  HAS_FAIL=1
fi

check_imports() {
  local group="$1"
  shift
  local modules=("$@")
  local miss
  miss="$("$PY_BIN" - "$group" "${modules[@]}" <<'PY'
import importlib
import sys

mods = sys.argv[2:]
missing = []
for m in mods:
    try:
        importlib.import_module(m)
    except Exception:
        missing.append(m)
print(",".join(missing))
PY
)"
  if [ -z "$miss" ]; then
    ok "$group modules import correctly"
    return
  fi
  warn "$group missing modules: $miss"
  HAS_WARN=1
}

check_imports "Core" streamlit numpy hnswlib tiktoken requests msal bs4
check_imports "Optional OCR/Attachments" lxml PIL pytesseract

PDF_PARSER_OK="$("$PY_BIN" - <<'PY'
import importlib
mods = ("pypdf", "PyPDF2")
ok = False
for m in mods:
    try:
        importlib.import_module(m)
        ok = True
        break
    except Exception:
        pass
print("1" if ok else "0")
PY
)"
if [ "$PDF_PARSER_OK" = "1" ]; then
  ok "Optional PDF parser available (pypdf or PyPDF2)"
else
  warn "No PDF parser found (install pypdf or PyPDF2 for PDF attachments)"
  HAS_WARN=1
fi
check_imports "Server" fastapi uvicorn jwt stripe pydantic

if [ -n "${EKSAMENAPP_AUTH_API_BASE:-}" ]; then
  info "Server mode env is set: EKSAMENAPP_AUTH_API_BASE=${EKSAMENAPP_AUTH_API_BASE}"
  if command -v curl >/dev/null 2>&1; then
    if curl -fsS "${EKSAMENAPP_AUTH_API_BASE}/health" >/dev/null 2>&1; then
      ok "Auth server /health reachable"
    else
      warn "Auth server not reachable on /health. Start ./scripts/run_auth_server.sh first."
      HAS_WARN=1
    fi
  else
    warn "curl not found, skipping /health check"
    HAS_WARN=1
  fi
else
  info "Local mode: EKSAMENAPP_AUTH_API_BASE is not set"
fi

echo
if [ "$HAS_FAIL" -eq 1 ]; then
  fail "Preflight failed. Fix errors before sharing to another machine."
  exit 1
fi

if [ "$HAS_WARN" -eq 1 ]; then
  warn "Preflight passed with warnings."
else
  ok "Preflight passed with no warnings."
fi

echo
info "Next steps:"
echo "  1) Start app: ./scripts/run_local.sh"
echo "  2) Server mode (optional): ./scripts/run_auth_server.sh"
echo "  3) Then in another shell: export EKSAMENAPP_AUTH_API_BASE=http://127.0.0.1:8080 && streamlit run Main.py"
