#!/bin/bash

# PermissionRequest Hook
# Triggered when Claude asks for user permission (Y/n prompts)
# Captures interactive prompts and can forward to mobile for remote approval
# Also extracts any assistant responses from the transcript that haven't been sent yet

# Source common utilities
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"

log "INFO" "PermissionRequest hook triggered"

# Read JSON input from stdin
INPUT=$(read_json_input)

log "DEBUG" "Input: $INPUT"

# Extract fields from permission request
SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty')
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty')
TOOL_INPUT=$(echo "$INPUT" | jq -c '.tool_input // {}')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
TRANSCRIPT_PATH=$(echo "$INPUT" | jq -r '.transcript_path // empty')

if [ -z "$SESSION_ID" ]; then
  log "ERROR" "No session_id found in permission request"
  exit 1
fi

# ============================================================
# FIRST: Extract and send any assistant responses from transcript
# This captures assistant text written BEFORE the tool permission request
# ============================================================

# Track sent message UUIDs to avoid duplicates across multiple PermissionRequest calls
SENT_UUIDS_FILE="${CODEVIBE_TMPDIR}/codevibe-claude-sent-uuids-${SESSION_ID}.txt"

if [ -n "$TRANSCRIPT_PATH" ] && [ -f "$TRANSCRIPT_PATH" ]; then
  log "DEBUG" "Reading transcript for assistant responses: $TRANSCRIPT_PATH"

  # Load already-sent UUIDs for filtering
  SENT_UUIDS_CONTENT=""
  if [ -f "$SENT_UUIDS_FILE" ]; then
    SENT_UUIDS_CONTENT=$(cat "$SENT_UUIDS_FILE")
  fi

  # Single jq invocation: find the most recent REAL user prompt, then take all
  # assistant messages after it in file order, filter out already-sent UUIDs,
  # extract text content.
  #
  # Previous implementation used a UUID-parent chain starting from the "last
  # user message" — but because the transcript includes tool_result entries as
  # type "user", the chain starting point was the last tool_result, not the
  # real user prompt. That meant only the ONE assistant message immediately
  # after the last tool_result was captured, and every earlier assistant text
  # block in the same turn was silently lost. This was bug #39 (2026-04-14):
  # users saw ~1/10 of mid-turn assistant text on mobile during long responses.
  #
  # Fix: a real user prompt has at least one content block of type "text".
  # Tool_result user messages have content blocks of type "tool_result". We
  # find the INDEX of the last real user prompt in file order, then take every
  # subsequent assistant message (they're all part of the current turn).
  ASSISTANT_MESSAGES=$(jq -r --slurp --arg sent "$SENT_UUIDS_CONTENT" '
    # Index of the last "real" user prompt. A real prompt has .message.content
    # that is EITHER a string (simple text prompt) OR an array containing at
    # least one content block of type "text" (mixed content). Tool_result user
    # messages have an array of content blocks where every block is type
    # "tool_result" — those are NOT real prompts and must be excluded.
    (
      [ range(0; length) as $i
        | select(.[$i].type == "user" and (
            (.[$i].message.content | type) == "string" or
            ((.[$i].message.content | type) == "array" and
             (.[$i].message.content | any(.type? == "text")))
          ))
        | $i
      ]
      | last // -1
    ) as $startIdx |
    if $startIdx < 0 then empty
    else
      # Parse sent UUIDs list
      ($sent | split("\n") | map(select(. != ""))) as $sentList |
      # Take messages after the real user prompt, filter to unsent assistant text
      .[($startIdx + 1):] |
      .[] |
      select(.type == "assistant") |
      select(.uuid as $u | $sentList | any(. == $u) | not) |
      {
        uuid: .uuid,
        text: ([.message.content[]? | select(.type == "text") | .text // empty] | join("\n\n"))
      } |
      select(.text | length > 0) |
      "\(.uuid)\t\(.text | @base64)"
    end
  ' "$TRANSCRIPT_PATH" 2>/dev/null)

  if [ -n "$ASSISTANT_MESSAGES" ]; then
    while IFS=$'\t' read -r MSG_UUID MSG_TEXT_B64; do
      if [ -z "$MSG_UUID" ] || [ -z "$MSG_TEXT_B64" ]; then
        continue
      fi

      # Decode base64-encoded text content (preserves newlines in markdown)
      MSG_TEXT=$(echo "$MSG_TEXT_B64" | base64 -d 2>/dev/null || echo "$MSG_TEXT_B64")

      ASSISTANT_PAYLOAD=$(jq -n \
        --arg session_id "$SESSION_ID" \
        --arg content "$MSG_TEXT" \
        --arg hook_event_name "PermissionRequest" \
        --arg type "ASSISTANT_RESPONSE" \
        '{
          session_id: $session_id,
          hook_event_name: $hook_event_name,
          type: $type,
          content: $content
        }')

      log "DEBUG" "Sending assistant response from PermissionRequest: ${MSG_TEXT:0:100}..."

      send_to_mcp "event" "$ASSISTANT_PAYLOAD" "$SESSION_ID"

      if [ $? -eq 0 ]; then
        log "INFO" "Assistant response sent successfully from PermissionRequest hook"
        echo "$MSG_UUID" >> "$SENT_UUIDS_FILE"
      else
        log "ERROR" "Failed to send assistant response from PermissionRequest hook"
      fi
    done <<< "$ASSISTANT_MESSAGES"
  fi
else
  log "WARN" "Transcript path not found or file doesn't exist: $TRANSCRIPT_PATH"
fi

# ============================================================
# SECOND: Send the INTERACTIVE_PROMPT event for the tool permission
# ============================================================

# Create question text based on tool type
# Include file path for file operations, command for Bash, etc.
QUESTION_TEXT=""
if [ "$TOOL_NAME" = "Edit" ]; then
  QUESTION_TEXT="Do you want to allow Edit operation on ${FILE_PATH}?"
elif [ "$TOOL_NAME" = "Write" ]; then
  QUESTION_TEXT="Do you want to allow Write operation to ${FILE_PATH}?"
elif [ "$TOOL_NAME" = "Read" ]; then
  QUESTION_TEXT="Do you want to allow Read operation on ${FILE_PATH}?"
elif [ "$TOOL_NAME" = "Bash" ]; then
  # Keep it simple - detailed command visible via "Tap to see details"
  QUESTION_TEXT="Do you want to allow Bash operation?"
elif [ -n "$TOOL_NAME" ] && [ -n "$FILE_PATH" ]; then
  QUESTION_TEXT="Do you want to allow ${TOOL_NAME} operation on ${FILE_PATH}?"
elif [ -n "$TOOL_NAME" ]; then
  QUESTION_TEXT="Do you want to allow ${TOOL_NAME} operation?"
else
  QUESTION_TEXT="Do you want to allow this operation?"
fi

log "DEBUG" "Creating INTERACTIVE_PROMPT for: $QUESTION_TEXT"

# Create INTERACTIVE_PROMPT event (options will be added dynamically by server via tmux parsing)
EVENT_PAYLOAD=$(jq -n \
  --arg session_id "$SESSION_ID" \
  --arg hook_event_name "PermissionRequest" \
  --arg type "INTERACTIVE_PROMPT" \
  --arg content "$QUESTION_TEXT" \
  --arg tool_name "$TOOL_NAME" \
  --argjson tool_input "$TOOL_INPUT" \
  '{
    session_id: $session_id,
    hook_event_name: $hook_event_name,
    type: $type,
    content: $content,
    metadata: {
      tool_name: $tool_name,
      tool_input: $tool_input
    }
  }')

log "DEBUG" "Event payload: $EVENT_PAYLOAD"

# Send INTERACTIVE_PROMPT event to MCP server (pass session_id for dynamic port lookup)
send_to_mcp "event" "$EVENT_PAYLOAD" "$SESSION_ID"

EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
  log "INFO" "PermissionRequest INTERACTIVE_PROMPT event sent successfully"
else
  log "ERROR" "Failed to send PermissionRequest event (exit code: $EXIT_CODE)"
fi

exit $EXIT_CODE
