#!/usr/bin/env bash
# Pro-default, fail-closed Factory front door.  It deliberately has no fallback path.
set -euo pipefail
CTL="${FACTORY_GPT_SOLWEBCTL:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/solwebctl}"
FACTORY_CMD="${FACTORY_GPT_FACTORY:-factory}"
effort=pro
if [[ ${1:-} == --effort ]]; then
  [[ $# -ge 4 ]] || { echo 'usage: factory-gpt [--effort medium|high|xhigh|pro] <adw> <prompt-or-path>' >&2; exit 2; }
  effort=$2; shift 2
fi
case "$effort" in medium|high|xhigh|pro) ;; *) echo "factory-gpt: unsupported effort: $effort" >&2; exit 2;; esac
[[ $# -eq 2 && -n $1 && -n $2 ]] || { echo 'usage: factory-gpt [--effort medium|high|xhigh|pro] <adw> <prompt-or-path>' >&2; exit 2; }
[[ -x "$CTL" ]] || { echo 'factory-gpt: solwebctl is not executable' >&2; exit 127; }
if [[ "$FACTORY_CMD" == */* ]]; then [[ -x "$FACTORY_CMD" ]] || { echo 'factory-gpt: factory is not executable' >&2; exit 127; }; else command -v "$FACTORY_CMD" >/dev/null || { echo 'factory-gpt: factory not found' >&2; exit 127; }; fi
# This is read-only and deliberately precedes daemon startup/session creation.
"$FACTORY_CMD" presets | grep -Eq "(^|[^[:alnum:]_-])gpt-sol-${effort}([^[:alnum:]_-]|$)" || { echo "factory-gpt: missing Factory preset gpt-sol-${effort}" >&2; exit 1; }
health="$("$CTL" ensure --json --seats 1)" || exit $?
python3 -c 'import json,sys; sys.exit(0 if json.loads(sys.argv[1]).get("ok") is True else 1)' "$health" || { echo 'factory-gpt: Sol provider is not ready' >&2; exit 1; }
exec "$FACTORY_CMD" --preset "gpt-sol-$effort" "$1" "$2"
