#!/bin/bash
# Orchestration helper: Create worktree and output spawn-ready context
# Usage: spawn-code-task.sh <product-slug> <requester> <requester-id> "<description>"
#
# This script:
# 1. Checks for concurrent work on the same product
# 2. Creates an isolated worktree with base_commit tracking
# 3. Outputs JSON with all context needed for sessions_spawn
#
# Main session uses this output to spawn subagent with proper isolation

set -e

SLUG=$1
REQUESTER=$2
REQUESTER_ID=$3
DESC=$4

if [ -z "$SLUG" ] || [ -z "$DESC" ]; then
  echo "Usage: spawn-code-task.sh <product-slug> <requester> <requester-id> \"<description>\"" >&2
  exit 1
fi

SKILL_DIR="$(dirname "$0")"
PRODUCT_DIR="/home/aria/products/$SLUG"
STATE_FILE="$PRODUCT_DIR/.worktree-state.json"
TASK_ID="task-$(date +%s)-$$"

# Check for active concurrent work
CONCURRENT_WORK=""
if [ -f "$STATE_FILE" ]; then
  ACTIVE_COUNT=$(jq '.active | length' "$STATE_FILE" 2>/dev/null || echo "0")
  if [ "$ACTIVE_COUNT" -gt 0 ]; then
    CONCURRENT_WORK=$(jq -r '.active | to_entries[] | "\(.value.requester): \(.value.description) (started \(.value.started))"' "$STATE_FILE" 2>/dev/null | tr '\n' '; ')
  fi
fi

# Create the worktree
WORK_DIR=$("$SKILL_DIR/create-worktree.sh" "$SLUG" "$TASK_ID" "$REQUESTER" "$REQUESTER_ID" "$DESC")

if [ -z "$WORK_DIR" ] || [ ! -d "$WORK_DIR" ]; then
  echo "ERROR: Failed to create worktree" >&2
  exit 1
fi

# Get the base commit for reference
BASE_COMMIT=$(jq -r ".active[\"$TASK_ID\"].base_commit" "$STATE_FILE" 2>/dev/null || echo "unknown")

# Build concurrent work warning if applicable
CONCURRENT_WARNING=""
if [ -n "$CONCURRENT_WORK" ]; then
  CONCURRENT_WARNING="⚠️ NOTE: Other work in progress on this product: $CONCURRENT_WORK\nYour changes will be checked for conflicts at merge time.\n\n"
fi

# Output JSON context for the spawn
cat << EOF
{
  "taskId": "$TASK_ID",
  "slug": "$SLUG",
  "workDir": "$WORK_DIR",
  "branch": "task/$TASK_ID",
  "baseCommit": "$BASE_COMMIT",
  "requester": "$REQUESTER",
  "requesterId": "$REQUESTER_ID",
  "description": "$DESC",
  "concurrentWork": $([ -n "$CONCURRENT_WORK" ] && echo "true" || echo "false"),
  "spawnTask": "${CONCURRENT_WARNING}## WORK DIRECTORY (MANDATORY)\nYou MUST work in this directory: $WORK_DIR\n\nDO NOT touch /home/aria/products/$SLUG/apps/main/ directly.\n\n## TASK\n$DESC\n\n## WHEN DONE\n1. git add -A\n2. git commit -m \"feat: <summary of changes>\"\n3. git push -u origin task/$TASK_ID\n4. Report completion - main session will handle merge\n\n## CRITICAL RULES\n- Work ONLY in $WORK_DIR\n- Commit ALL changes before finishing\n- Do NOT run the app (main session handles deployment)\n- Do NOT attempt to merge (main session handles this)\n- If you need to install dependencies: cd $WORK_DIR && pnpm install"
}
EOF
