#!/bin/bash
# =====================================================
# UserPromptSubmit Hook - Workflow Plugin
# =====================================================
#
# IMPLEMENTS REQUIREMENTS:
#   REQ-d00018: Git Hook Implementation
#   REQ-d00068: Enhanced Workflow New Work Detection
#   REQ-o00053: Branch Protection Enforcement
#
# Detects task-switching language and recommends
# ticket management before work starts.
#
# This hook provides proactive workflow guidance by
# analyzing user prompts for patterns that indicate:
# - Starting new implementation work
# - Switching to different task scope
# - Creating new features/components
#
# =====================================================

set -e

# Read prompt from stdin
PROMPT=$(cat)

# Find plugin directory
PLUGIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BRANCH_HEALTH_SCRIPT="$PLUGIN_DIR/scripts/branch-health-check.sh"

# Get current active ticket
ACTIVE_TICKET=$("$PLUGIN_DIR/scripts/get-active-ticket.sh" --format=id 2>/dev/null || echo "")

# ===================================================
# BRANCH HEALTH CHECK (P0 - Highest Priority)
# ===================================================
# Block work on merged/squash-merged branches before any other checks

BRANCH_BLOCKED=false
BRANCH_BLOCK_MSG=""

if [ -f "$BRANCH_HEALTH_SCRIPT" ]; then
    BRANCH_HEALTH_JSON=$("$BRANCH_HEALTH_SCRIPT" --format=json 2>/dev/null || echo '{"status": "error", "canWork": true}')
    BRANCH_STATUS=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.status // "error"')
    CAN_WORK=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.canWork // true')
    BRANCH_NAME=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.branch // "unknown"')
    BRANCH_MESSAGE=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.message // ""')
    BRANCH_RECOMMENDATION=$(echo "$BRANCH_HEALTH_JSON" | jq -r '.recommendation // ""')

    if [ "$CAN_WORK" = "false" ]; then
        BRANCH_BLOCKED=true

        case $BRANCH_STATUS in
            merged|squash-merged)
                BRANCH_BLOCK_MSG="⛔ CANNOT WORK ON MERGED BRANCH

Branch: $BRANCH_NAME
Status: $BRANCH_STATUS
$BRANCH_MESSAGE

This branch has already been merged into main.
Continuing work here will create divergence and confusion.

🚨 ACTION REQUIRED:

1. If you need to continue this work, create a new branch:
   git checkout -b feature/NEW-TICKET-ID origin/main

2. If the work is complete, you can delete this branch:
   $BRANCH_RECOMMENDATION

3. If this is unexpected, verify the merge status:
   git branch -r --merged origin/main | grep $BRANCH_NAME

The workflow enforcer is blocking this action to prevent accidental work on merged branches."
                ;;
            protected)
                BRANCH_BLOCK_MSG="🛡️ CANNOT WORK ON PROTECTED BRANCH

You are on branch: $BRANCH_NAME

Protected branches (main, master) require work on feature branches.

🚨 ACTION REQUIRED:

Create a feature branch before making changes:
  git checkout -b feature/TICKET-ID origin/main"
                ;;
            detached)
                BRANCH_BLOCK_MSG="⚠️ DETACHED HEAD STATE

You are not on a branch. Git operations may not work as expected.

🚨 ACTION REQUIRED:

Create or checkout a branch:
  git checkout -b feature/TICKET-ID"
                ;;
        esac
    fi
fi

# If branch is blocked, output warning and exit early
if [ "$BRANCH_BLOCKED" = true ]; then
    jq -n \
        --arg msg "$BRANCH_BLOCK_MSG" \
        --arg status "$BRANCH_STATUS" \
        --arg branch "$BRANCH_NAME" \
        '{
          "systemMessage": $msg,
          "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": ("Branch health check failed: " + $status + " on " + $branch + ". Work blocked until branch issue is resolved.")
          }
        }'
    exit 0
fi

# Pattern matching scores
TASK_SWITCH_SCORE=0
NEW_FEATURE_SCORE=0
PR_MERGE_DETECTED=false

# ===================================================
# PR MERGE DETECTION (Highest priority)
# ===================================================

# Check for PR merge mentions
if echo "$PROMPT" | grep -qiE "(PR|pull request) ?(#[0-9]+)? ?(is|was|has been)? ?(merged|merge successful|merge complete)|(merged? (the )?PR)|(merge successful)"; then
    PR_MERGE_DETECTED=true
fi

# ===================================================
# HIGH-PRIORITY PATTERNS (Strong task switch indicators)
# ===================================================

# Explicit scope change language
if echo "$PROMPT" | grep -qiE "(completely (different|unrelated|separate))|(instead,? let'?s)"; then
    TASK_SWITCH_SCORE=$((TASK_SWITCH_SCORE + 10))
fi

# Direct pivot language
if echo "$PROMPT" | grep -qiE "(switch to|move on to|pivot to|change direction)"; then
    TASK_SWITCH_SCORE=$((TASK_SWITCH_SCORE + 10))
fi

# Structural change patterns (high confidence of new work)
if echo "$PROMPT" | grep -qiE "rename .* to|move .* to"; then
    TASK_SWITCH_SCORE=$((TASK_SWITCH_SCORE + 8))
fi

# ===================================================
# MEDIUM-PRIORITY PATTERNS (New feature indicators)
# ===================================================

# Starting new implementation work
if echo "$PROMPT" | grep -qiE "let'?s (now |also |)(create|build|implement|add|design|make)"; then
    NEW_FEATURE_SCORE=$((NEW_FEATURE_SCORE + 6))
    TASK_SWITCH_SCORE=$((TASK_SWITCH_SCORE + 4))
fi

# Can you / I want to (implementation request)
if echo "$PROMPT" | grep -qiE "(can you|i want to|we should) (create|build|implement|add|make)"; then
    NEW_FEATURE_SCORE=$((NEW_FEATURE_SCORE + 5))
fi

# New component creation
if echo "$PROMPT" | grep -qiE "new (file|directory|component|module|plugin|feature|script|function|class)"; then
    NEW_FEATURE_SCORE=$((NEW_FEATURE_SCORE + 6))
fi

# Refactoring work
if echo "$PROMPT" | grep -qiE "(refactor|restructure|redesign|rewrite)"; then
    TASK_SWITCH_SCORE=$((TASK_SWITCH_SCORE + 5))
fi

# Bug fix work
if echo "$PROMPT" | grep -qiE "(fix (the |a |)|bug|issue|error|problem) (in |with |at )"; then
    NEW_FEATURE_SCORE=$((NEW_FEATURE_SCORE + 4))
fi

# Documentation work
if echo "$PROMPT" | grep -qiE "(update|write|add|create) (the |)(docs|documentation|README)"; then
    NEW_FEATURE_SCORE=$((NEW_FEATURE_SCORE + 3))
fi

# ===================================================
# LOW-PRIORITY PATTERNS (Planning/design indicators)
# ===================================================

# Planning work (might be new scope)
if echo "$PROMPT" | grep -qiE "(plan (a |the |)|design (a |the |)|architecture for)"; then
    NEW_FEATURE_SCORE=$((NEW_FEATURE_SCORE + 3))
fi

# Next steps language
if echo "$PROMPT" | grep -qiE "next,? (let'?s|we need to|i want to)"; then
    TASK_SWITCH_SCORE=$((TASK_SWITCH_SCORE + 3))
fi

# ===================================================
# DECISION LOGIC
# ===================================================

SHOULD_WARN=false
WARNING_MSG=""

# PR merge detected (highest priority)
if [ "$PR_MERGE_DETECTED" = true ]; then
    SHOULD_WARN=true
    if [ -n "$ACTIVE_TICKET" ]; then
        WARNING_MSG="🎉 PR MERGE DETECTED

Active ticket: $ACTIVE_TICKET

The workflow-enforcer agent will help you:
1. Verify the PR merge status
2. Release the ticket with PR reference
3. Add completion comment to Linear
4. Clean up merged branches (if safe)

Proceeding with automatic workflow cleanup..."
    else
        WARNING_MSG="🎉 PR MERGE DETECTED

No active ticket found.

The workflow-enforcer agent will help verify the merge status and determine
if any cleanup is needed."
    fi

# High-confidence task switch detected
elif [ $TASK_SWITCH_SCORE -ge 8 ]; then
    SHOULD_WARN=true
    if [ -n "$ACTIVE_TICKET" ]; then
        WARNING_MSG="🔄 TASK CONTEXT SHIFT DETECTED

Your prompt suggests starting work that may be unrelated to the current ticket.

Current active ticket: $ACTIVE_TICKET

Consider:
1. Is this work part of $ACTIVE_TICKET? → Continue as-is
2. Different ticket entirely? → Switch tickets:
   tools/anspar-cc-plugins/plugins/workflow/scripts/switch-ticket.sh NEW-TICKET \"reason\"
3. Quick fix/investigation? → Maybe continue, be mindful of scope

This is a gentle reminder - you decide the scope."
    else
        WARNING_MSG="⚠️  NO ACTIVE TICKET

You're about to start implementation work without claiming a ticket.

🎯 Options:

1. **Create a new ticket** (recommended):
   Just say: \"Create a ticket for [your work description]\"

   The ticket-creation-agent will help you create a well-structured ticket
   with smart defaults from your git context, then offer to claim it.

2. **Claim an existing ticket**:
   tools/anspar-cc-plugins/plugins/workflow/scripts/claim-ticket.sh TICKET-ID

3. **Explore first**:
   Continue without claiming - git hooks will enforce at commit time."
    fi

# New feature work detected
elif [ $NEW_FEATURE_SCORE -ge 6 ]; then
    SHOULD_WARN=true
    if [ -n "$ACTIVE_TICKET" ]; then
        WARNING_MSG="✨ NEW FEATURE WORK DETECTED

Your prompt suggests starting new feature development.

Current active ticket: $ACTIVE_TICKET

Consider:
1. Is this new feature part of $ACTIVE_TICKET's scope? → Continue
2. Should this be a separate ticket? → Let me help create one:
   Just ask: \"Create a ticket for [your feature description]\"

   The ticket-creation-agent will guide you through smart ticket creation.

Reminder: Keep ticket scope focused for better traceability."
    else
        WARNING_MSG="📋 NEW FEATURE WORK DETECTED

You're starting new feature work without an active ticket.

🎯 Quick action: Let me help you create a ticket!

Just say: \"Create a ticket for [your feature description]\"

The intelligent ticket-creation-agent will:
- Infer details from your git context
- Suggest appropriate labels and priority
- Guide you through ticket creation
- Offer to claim it for you

Or explore first: Workflow is enforced at commit time, so you can start
investigating and create a ticket when ready."
    fi
fi

# ===================================================
# OUTPUT JSON RESPONSE
# ===================================================

if [ "$SHOULD_WARN" = true ]; then
    # Generate warning with context for main Claude agent
    ADDITIONAL_CONTEXT="Workflow analysis: Task switch score=$TASK_SWITCH_SCORE, New feature score=$NEW_FEATURE_SCORE. Active ticket: ${ACTIVE_TICKET:-none}. User prompt suggests potential scope change or new work."

    jq -n \
        --arg msg "$WARNING_MSG" \
        --arg ctx "$ADDITIONAL_CONTEXT" \
        '{
          "systemMessage": $msg,
          "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": $ctx
          }
        }'
else
    # No warning needed - pass through silently
    echo '{"continue": true}'
fi

exit 0
