#!/bin/bash
# Example: run_dev hook
#
# This hook starts a dev server and optionally creates a tunnel for sharing.
# It reports the server URL back to dmux via the HTTP API.

set -e

echo "[Hook] Starting dev server for $DMUX_SLUG"

cd "$DMUX_WORKTREE_PATH"
API_URL="http://localhost:$DMUX_SERVER_PORT/api/panes/$DMUX_PANE_ID/dev"

# Update status: starting
curl -s -X PUT "$API_URL" \
  -H "Content-Type: application/json" \
  -d '{"status": "running"}' > /dev/null

# Start dev server in background
# Adjust the command for your project (pnpm dev, npm run dev, vite, etc.)
LOG_FILE="/tmp/dmux-dev-$DMUX_PANE_ID.log"
pnpm dev > "$LOG_FILE" 2>&1 &
DEV_PID=$!

# Wait for server to be ready
echo "[Hook] Waiting for dev server to start..."
sleep 5

# Detect port from log output
# Adjust the grep pattern for your dev server's output format
PORT=$(grep -oP '(?<=localhost:)\d+' "$LOG_FILE" | head -1)

if [ -z "$PORT" ]; then
  echo "[Hook] Warning: Could not detect port from logs, using default 3000"
  PORT=3000
fi

LOCAL_URL="http://localhost:$PORT"
echo "[Hook] Dev server running at $LOCAL_URL"

# Optional: Create a public tunnel (uncomment to enable)
# Requires ngrok, cloudflared, or another tunneling tool

# Example with cloudflared:
# TUNNEL_URL=$(cloudflared tunnel --url "$LOCAL_URL" 2>&1 | \
#   grep -oP 'https://[a-z0-9-]+\.trycloudflare\.com' | head -1)

# Example with ngrok:
# TUNNEL_URL=$(ngrok http $PORT --log=stdout 2>&1 | \
#   grep -oP 'url=https://[^"]+' | head -1 | cut -d= -f2)

# For now, just use local URL (uncomment tunnel code above to enable)
FINAL_URL="$LOCAL_URL"

# Report status back to dmux
curl -s -X PUT "$API_URL" \
  -H "Content-Type: application/json" \
  -d "{\"status\": \"running\", \"url\": \"$FINAL_URL\"}" > /dev/null

echo "[Hook] Dev server ready at: $FINAL_URL"
echo "[Hook] Dev server PID: $DEV_PID"
echo "[Hook] Log file: $LOG_FILE"
