#!/bin/bash
# Create a worktree for isolated task work
# Usage: create-worktree.sh <product-slug> <task-id> <requester> <requester-id> <description>

set -e

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

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

PRODUCT_DIR="/home/aria/products/$SLUG"
MAIN_DIR="$PRODUCT_DIR/apps/main"
WORKTREE_DIR="$PRODUCT_DIR/worktrees/$TASK_ID"
STATE_FILE="$PRODUCT_DIR/.worktree-state.json"

# Verify product exists
if [ ! -d "$MAIN_DIR" ]; then
  echo "ERROR: Product main directory not found: $MAIN_DIR" >&2
  exit 1
fi

# Create worktrees directory
mkdir -p "$PRODUCT_DIR/worktrees"

# Ensure gitignore entries
GITIGNORE="$PRODUCT_DIR/.gitignore"
if [ ! -f "$GITIGNORE" ]; then
  touch "$GITIGNORE"
fi
grep -q "^\.worktree-state\.json$" "$GITIGNORE" 2>/dev/null || echo ".worktree-state.json" >> "$GITIGNORE"
grep -q "^worktrees/$" "$GITIGNORE" 2>/dev/null || echo "worktrees/" >> "$GITIGNORE"

# Create worktree (suppress git output)
cd "$MAIN_DIR"
git fetch origin >/dev/null 2>&1 || true

# Record base commit BEFORE creating worktree
BASE_COMMIT=$(git rev-parse HEAD)

git worktree add "$WORKTREE_DIR" -b "task/$TASK_ID" origin/main >/dev/null 2>&1 || \
  git worktree add "$WORKTREE_DIR" -b "task/$TASK_ID" main >/dev/null 2>&1

# Initialize state file if needed
if [ ! -f "$STATE_FILE" ]; then
  echo '{"active":{},"recent_merges":[]}' > "$STATE_FILE"
fi

# Ensure recent_merges array exists (for older state files)
if ! jq -e '.recent_merges' "$STATE_FILE" >/dev/null 2>&1; then
  jq '. + {recent_merges: []}' "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"
fi

# Add entry to state with base_commit for divergence detection
jq --arg id "$TASK_ID" \
   --arg branch "task/$TASK_ID" \
   --arg path "worktrees/$TASK_ID" \
   --arg req "${REQUESTER:-unknown}" \
   --arg req_id "${REQUESTER_ID:-}" \
   --arg desc "${DESC:-No description}" \
   --arg started "$(date -Iseconds)" \
   --arg base "$BASE_COMMIT" \
   '.active[$id] = {branch: $branch, path: $path, requester: $req, requester_id: $req_id, description: $desc, started: $started, base_commit: $base}' \
   "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"

# Patch next.config.ts to allow Symphony embedding during Build Copilot session
NEXT_CONFIG="$WORKTREE_DIR/next.config.ts"
if [ -f "$NEXT_CONFIG" ]; then
  # Remove X-Frame-Options entirely (CSP frame-ancestors supersedes it)
  sed -i "/{ key: 'X-Frame-Options', value: 'DENY' },/d" "$NEXT_CONFIG"
  sed -i "/{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },/d" "$NEXT_CONFIG"
  # Allow Symphony to embed this app in an iframe
  sed -i "s/frame-ancestors 'none'/frame-ancestors https:\/\/symphony.symph.co https:\/\/*.dev.apps.symph.co/" "$NEXT_CONFIG"

  # Commit the patch in the worktree branch
  cd "$WORKTREE_DIR"
  if ! git diff --quiet next.config.ts 2>/dev/null; then
    git add next.config.ts
    git commit -m "chore(worktree): allow Symphony embedding for Build Copilot" --no-verify 2>/dev/null || true
  fi
fi

echo "$WORKTREE_DIR"
