#!/usr/bin/env bash
# red-cargo — built-in pre_worktree library hook for Rust projects.
#
# Contract (ADR 0026, PRD #207, issue #211):
#   stdin   — JSON object: pre_worktree context (issue, target, branch, env).
#   applicability — decided by the Node resolver before this leaf runs.
#   stdout  — a JSON object that merges
#             {env: {CARGO_TARGET_DIR: <slot dir>}} into the context.
#   exit    — 0. Never aborts the chain.
#
# Side effect: mkdir -p the slot target dir so cargo can use it immediately.
# CARGO_TARGET_DIR=${RED_AFK_CARGO_TARGET_BASE:-/opt/cargo-target}/slot-${RED_AFK_SLOT:-0}
# so each worker slot gets its own target directory and Cargo never
# serializes on .cargo-lock between workers.
#
# Env contract (RED_AFK_* exported by the orchestrator):
#   RED_AFK_SLOT                — worker slot number (0-based); defaults to 0.
#   RED_AFK_CARGO_TARGET_BASE   — base dir for slot target dirs; defaults to
#                                 /opt/cargo-target. Set in .red/config.yaml
#                                 via afk.cargo_target_base or by environment.
#
# Shadowing: place a same-named file in .red/hooks/red-cargo to replace this
# default with a project-local variant. An empty (exit-0) file disables it.

set -u

ctx="$(timeout "${RED_SKILLS_HOOK_STDIN_TIMEOUT_S:-5s}" cat 2>/dev/null || true)"
[ -n "$ctx" ] || ctx='{}'

slot="${RED_AFK_SLOT:-0}"
base="${RED_AFK_CARGO_TARGET_BASE:-/opt/cargo-target}"
target_dir="${base}/slot-${slot}"

mkdir -p "$target_dir" 2>/dev/null || true

printf '%s' "$ctx" | jq -c \
  --arg t "$target_dir" \
  '. + {env: ((.env // {}) + {CARGO_TARGET_DIR: $t})}'
