#!/bin/bash
# Example: worktree_created hook
#
# This hook runs after a new worktree is created and the agent is launched.
# Use it to set up the worktree environment (install deps, copy configs, etc.)

set -e  # Exit on error

echo "[Hook] Setting up worktree: $DMUX_SLUG"

cd "$DMUX_WORKTREE_PATH"

# Install dependencies in background (don't block dmux)
if [ -f "pnpm-lock.yaml" ]; then
  echo "[Hook] Installing dependencies with pnpm..."
  pnpm install --prefer-offline &
elif [ -f "package-lock.json" ]; then
  echo "[Hook] Installing dependencies with npm..."
  npm install &
elif [ -f "yarn.lock" ]; then
  echo "[Hook] Installing dependencies with yarn..."
  yarn install &
fi

# Copy environment file if it exists
if [ -f "$DMUX_ROOT/.env.local" ]; then
  echo "[Hook] Copying .env.local"
  cp "$DMUX_ROOT/.env.local" "$DMUX_WORKTREE_PATH/.env.local"
fi

# Set custom git config for this worktree
echo "[Hook] Configuring git"
git config user.name "dmux-agent/$DMUX_SLUG"
git config user.email "agent@dmux.local"

# Create a log entry
echo "[$(date)] Created worktree: $DMUX_SLUG | Agent: $DMUX_AGENT | Prompt: $DMUX_PROMPT" \
  >> "$DMUX_ROOT/.dmux/worktree_history.log"

echo "[Hook] Worktree setup complete!"
