#!/usr/bin/env bash
set -Eeuo pipefail
: "${ROBORTO_PROJECT_ROOT:?}"
: "${ROBORTO_TASK_ID:?}"
: "${ROBORTO_WORKTREE:?}"
: "${ROBORTO_RUN_DIR:?}"
project="bortstack-testtask-${ROBORTO_TASK_ID}"
compose() {
  docker compose --project-name "$project" --file "$ROBORTO_PROJECT_ROOT/.roborto/testtask-compose.yml" "$@"
}
case "${1:-}" in
  validate)
    command -v python3 >/dev/null
    command -v docker >/dev/null
    docker compose version >/dev/null
    docker info >/dev/null 2>&1 || { echo 'testtask: Docker daemon is unavailable or permission denied.' >&2; exit 1; }
    compose config --quiet
    ;;
  prepare)
    python3 "$ROBORTO_PROJECT_ROOT/scripts/create-test-snapshot.py" "$ROBORTO_TASK_ID"
    # Refuse collisions with an existing environment; cleanup owns only this run.
    if [[ -n "$(compose ps --all --quiet)" ]]; then
      echo "testtask: existing $project containers found; stop their owning session first." >&2
      exit 1
    fi
    touch "$ROBORTO_RUN_DIR/owns-compose"
    compose build
    compose up --detach --no-build
    if ! python3 - <<'READY'
import time
import urllib.request
urls = ['http://127.0.0.1:15001/api/health/ready', 'http://127.0.0.1:18081/', 'http://127.0.0.1:18081/api/health/ready']
for url in urls:
    for attempt in range(120):
        try:
            with urllib.request.urlopen(url, timeout=2) as response:
                if response.status == 200:
                    break
        except (OSError, urllib.error.URLError):
            pass
        time.sleep(0.25)
    else:
        raise SystemExit(f'testtask: readiness failed for {url}')
print('HTTP frontend and direct/proxied API readiness passed.')
READY
    then
      compose logs --tail 40 >&2
      exit 1
    fi
    ;;
  start-backend) compose logs --follow api ;;
  start-frontend) compose logs --follow web ;;
  credentials)
    python3 - <<'PY'
import urllib.request
for url in ['http://127.0.0.1:15001/api/health/ready', 'http://127.0.0.1:18081/', 'http://127.0.0.1:18081/api/health/ready']:
    with urllib.request.urlopen(url, timeout=10) as response:
        assert response.status == 200, url
print('Ready: http://127.0.0.1:18081/ — inherited starter; registration closed, email disabled; no login required.')
PY
    ;;
  cleanup)
    if [[ -f "$ROBORTO_RUN_DIR/owns-compose" ]]; then
      compose down --volumes --remove-orphans
    fi
    ;;
  *) echo 'testtask: unsupported hook operation' >&2; exit 64 ;;
esac
