#!/usr/bin/env bash

harness_warn_dev_engine() {
  local reason="$1" harness_root="$2" sha dirty
  sha="$(git -C "$harness_root" rev-parse HEAD 2>/dev/null || printf unknown)"
  dirty="clean"
  if [[ -n "$(git -C "$harness_root" status --porcelain 2>/dev/null || true)" ]]; then
    dirty="dirty"
  fi
  printf 'WARNING: %s engine checkout=%s sha=%s dirty=%s\n' "$reason" "$harness_root" "$sha" "$dirty" >&2
}

harness_resolve_engine_root() {
  local harness_root="$1" harness_home="$2" require_rel="$3" caller="$4"
  local current_file="${harness_home}/engine/CURRENT" version bundle_root
  if [[ "${HARNESS_ENGINE_DEV:-}" == "1" ]]; then
    harness_warn_dev_engine "HARNESS_ENGINE_DEV=1" "$harness_root"
    printf '%s\n' "$harness_root"
    return
  fi
  if [[ ! -s "$current_file" ]]; then
    echo "${caller}: released engine pointer missing: ${current_file}" >&2
    return 2
  fi
  if ! version="$(cat "$current_file" 2>/dev/null)"; then
    echo "${caller}: invalid engine CURRENT at ${current_file}" >&2
    return 2
  fi
  version="${version//[$'\t\r\n ']/}"
  if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "${caller}: invalid engine version in ${current_file}: ${version}" >&2
    return 2
  fi
  bundle_root="${harness_home}/engine/versions/${version}"
  if [[ ! -s "${bundle_root}/ENGINE_SHA" || ! -f "${bundle_root}/${require_rel}" ]]; then
    echo "${caller}: invalid engine bundle at ${bundle_root} (missing ${require_rel}; CURRENT: ${current_file})" >&2
    return 2
  fi
  printf '%s\n' "$bundle_root"
}
