#!/usr/bin/env bash
# Services — ML service lifecycle (LLM + CAPTCHA solver)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/core"

TALENT_SCOUT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
LLM_ROOT="$(cd "$TALENT_SCOUT_ROOT/../../features/conversation-assistant/ml-service" && pwd)"
CAPTCHA_ROOT="$TALENT_SCOUT_ROOT/packages/captcha-solver/ml-service"

services_start_llm() {
  if [ ! -f "$LLM_ROOT/.venv/bin/python" ]; then
    err "LLM venv not found at $LLM_ROOT/.venv"
    return 1
  fi
  log "Starting LLM service on :${LLM_PORT}..."
  cd "$LLM_ROOT"
  exec .venv/bin/python -m uvicorn src.main:app --host 127.0.0.1 --port "$LLM_PORT"
}

services_start_captcha() {
  if [ ! -f "$CAPTCHA_ROOT/.venv/bin/python" ]; then
    err "CAPTCHA venv not found at $CAPTCHA_ROOT/.venv"
    return 1
  fi
  log "Starting CAPTCHA solver on :${CAPTCHA_PORT}..."
  cd "$CAPTCHA_ROOT"
  exec env PYTHONPATH=src \
    GPUBOSS_REDIS_URL="redis://localhost:${MODEL_BOSS_REDIS_PORT:-26400}" \
    CAPTCHA_SOLVER_FORCED_STYLE="${CAPTCHA_SOLVER_FORCED_STYLE:-line-strike}" \
    CAPTCHA_SOLVER_STYLE_MODEL_OVERRIDES='{"line-strike":"parseq_line-strike_v1_81pct.pt"}' \
    .venv/bin/python -m uvicorn talent_scout_captcha.api.server:app \
    --host 127.0.0.1 --port "$CAPTCHA_PORT"
}

services_wait_llm() {
  wait_http "LLM service :${LLM_PORT}" "http://localhost:${LLM_PORT}/health" 120
}

services_wait_captcha() {
  wait_http "CAPTCHA solver :${CAPTCHA_PORT}" "http://localhost:${CAPTCHA_PORT}/health" 60
}

services_wait_all() {
  services_wait_llm & services_wait_captcha &
  wait
}

services_status() {
  if curl -sf "http://localhost:${LLM_PORT}/health" > /dev/null 2>&1; then
    ok "LLM service      :${LLM_PORT}  healthy"
  else
    warn "LLM service      :${LLM_PORT}  not running"
  fi

  if curl -sf "http://localhost:${CAPTCHA_PORT}/health" > /dev/null 2>&1; then
    ok "CAPTCHA solver   :${CAPTCHA_PORT}  healthy"
  else
    warn "CAPTCHA solver   :${CAPTCHA_PORT}  not running"
  fi
}
