#!/bin/bash

# Story Validation Hook for Claude Code
# Implements R.O.C.K.E.T. framework validation for story files
# Usage: story-validation-hook.sh <file_path>

set -euo pipefail

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="$SCRIPT_DIR/../validation.log"
VALIDATION_ENGINE="$SCRIPT_DIR/story-validation-engine.js"
SCORING_SYSTEM="$SCRIPT_DIR/story-scoring-system.js"

# Input validation
if [ $# -ne 1 ]; then
    echo "Error: Usage: $0 <file_path>" >&2
    exit 1
fi

FILE_PATH="$1"

# Security: Validate file path to prevent injection attacks
if [[ "$FILE_PATH" =~ [^a-zA-Z0-9/_.-] ]]; then
    echo "Error: Invalid characters in file path" >&2
    exit 1
fi

# Security: Ensure file exists and is readable
if [ ! -f "$FILE_PATH" ]; then
    echo "Error: File does not exist: $FILE_PATH" >&2
    exit 1
fi

if [ ! -r "$FILE_PATH" ]; then
    echo "Error: File is not readable: $FILE_PATH" >&2
    exit 1
fi
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Logging function
log() {
    echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}

# Check if file is a story file
if [[ ! "$FILE_PATH" =~ .*stories/.*\.md$ ]]; then
    log "INFO: File $FILE_PATH is not a story file, skipping validation"
    exit 0
fi

# Check if content was generated by sub-agent
SUB_AGENT_GENERATED=false
if [ -f "$FILE_PATH" ]; then
    # Look for sub-agent indicators in the file content
    if grep -q "Agent Model Used" "$FILE_PATH" 2>/dev/null || 
       grep -q "🤖 Generated with \[Claude Code\]" "$FILE_PATH" 2>/dev/null ||
       grep -q "Sub-agent:" "$FILE_PATH" 2>/dev/null; then
        SUB_AGENT_GENERATED=true
        log "INFO: Sub-agent generated content detected in $FILE_PATH"
    fi
fi

log "Starting story validation for: $FILE_PATH"

# Check if validation engine exists
if [ ! -f "$VALIDATION_ENGINE" ]; then
    log "ERROR: Validation engine not found at $VALIDATION_ENGINE"
    exit 1
fi

# Check if scoring system exists
if [ ! -f "$SCORING_SYSTEM" ]; then
    log "ERROR: Scoring system not found at $SCORING_SYSTEM"
    exit 1
fi

# Run validation engine with sub-agent context
log "Running R.O.C.K.E.T. validation engine..."
if [ "$SUB_AGENT_GENERATED" = true ]; then
    log "INFO: Applying sub-agent validation rules"
    # Pass sub-agent flag to validation engine
    if ! VALIDATION_RESULT=$(node "$VALIDATION_ENGINE" "$FILE_PATH" --sub-agent 2>&1); then
        log "ERROR: Sub-agent validation engine failed: $VALIDATION_RESULT"
        exit 1
    fi
else
    if ! VALIDATION_RESULT=$(node "$VALIDATION_ENGINE" "$FILE_PATH" 2>&1); then
        log "ERROR: Validation engine failed: $VALIDATION_RESULT"
        exit 1
    fi
fi

# Parse validation result with error handling
SCORE=$(echo "$VALIDATION_RESULT" | grep "SCORE:" | cut -d: -f2 | tr -d ' ')
STATUS=$(echo "$VALIDATION_RESULT" | grep "STATUS:" | cut -d: -f2 | tr -d ' ')

# Validate parsed values
if [ -z "$SCORE" ] || [ -z "$STATUS" ]; then
    log "ERROR: Failed to parse validation result"
    log "Raw output: $VALIDATION_RESULT"
    exit 1
fi

log "Validation completed - Score: $SCORE, Status: $STATUS"

# Apply quality gate (7+ required for approval)
QUALITY_THRESHOLD=7

# Convert score to integer for comparison (multiply by 10 to handle decimals)
# Check if bc is available, fallback to awk
if command -v bc >/dev/null 2>&1; then
    SCORE_INT=$(echo "$SCORE * 10" | bc -l | cut -d. -f1)
    THRESHOLD_INT=$(echo "$QUALITY_THRESHOLD * 10" | bc -l)
else
    SCORE_INT=$(echo "$SCORE" | awk '{print int($1 * 10)}')
    THRESHOLD_INT=$(echo "$QUALITY_THRESHOLD" | awk '{print int($1 * 10)}')
fi

if (( SCORE_INT >= THRESHOLD_INT )); then
    log "✅ PASS: Story validation successful (Score: $SCORE >= $QUALITY_THRESHOLD)"
    
    # Generate success notification
    cat <<EOF
{
    "continue": true,
    "decision": "approve",
    "reason": "Story validation passed with score $SCORE/10"
}
EOF
    exit 0
else
    log "❌ FAIL: Story validation failed (Score: $SCORE < $QUALITY_THRESHOLD)"
    log "Validation details: $VALIDATION_RESULT"
    
    # Block execution and provide feedback
    cat <<EOF
{
    "continue": false,
    "decision": "block", 
    "reason": "Story validation failed with score $SCORE/10. Minimum required: $QUALITY_THRESHOLD/10. Please fix issues and try again."
}
EOF
    exit 1
fi