#!/usr/bin/env bash
# task-status <taskId> — introspect the actual runtime state.
#
# Returns the truth from docker / git / process listings rather than
# trusting the Task row. Used by POST /api/tasks/:id/reconcile to detect
# drift after a manual `docker compose down` or similar.

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=_common.sh
. "$SCRIPT_DIR/_common.sh"

[ "$#" -eq 1 ] || emit_err "BAD_ARGS" "usage: task-status <taskId>" "args"

task_id="$1"
UAI_TASK_ID="$task_id"
setup_err_trap

step "TASK_NOT_FOUND" "read task row"
task_json=$(db_get_task "$task_id")
[ "$(jq 'length' <<<"$task_json")" -ge 1 ] \
  || emit_err "TASK_NOT_FOUND" "no such task: $task_id" "read task row"

compose_project=$(jq -r '.[0].compose_project // ""' <<<"$task_json")
worktree_path=$(jq -r '.[0].worktree_path // ""' <<<"$task_json")

# Containers running under this compose project, JSON array of names.
step "DOCKER_PS_FAILED" "docker ps"
containers_json="[]"
if [ -n "$compose_project" ]; then
  raw=$(docker ps --filter "label=com.docker.compose.project=$compose_project" --format '{{.Names}}' || true)
  if [ -n "$raw" ]; then
    containers_json=$(printf '%s\n' "$raw" | jq -R . | jq -sc .)
  fi
fi

# Compose running iff at least one container is up.
if [ "$containers_json" = "[]" ]; then
  compose_running="false"
else
  compose_running="true"
fi

# Worktree present iff the directory exists.
worktree_present="false"
if [ -n "$worktree_path" ] && [ -d "$worktree_path" ]; then
  worktree_present="true"
fi

emit_ok "$(jq -nc \
  --argjson cr "$compose_running" \
  --argjson cs "$containers_json" \
  --argjson wp "$worktree_present" \
  '{composeRunning:$cr,containers:$cs,worktreePresent:$wp}')"
