#!/bin/bash
# AutoWorkflow Pre-Edit Hook (v3.7.0 - Fail-Closed Design)
# Runs on: PreToolUse for Write/Edit tools
# Purpose: BLOCK edits by default unless workflow state is properly set
#
# DESIGN PRINCIPLE: Fail-closed
# - If state is not initialized → BLOCK (auto-init as feature)
# - If plan not approved → BLOCK
# - If suggestions not shown (feature tasks) → BLOCK
# - If multiple edits per turn → BLOCK
# - Only allow edit if ALL checks pass

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'

# Project directory (use env var if set, otherwise current directory)
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-.}"

# State directory
STATE_DIR="$PROJECT_DIR/.claude/.autoworkflow"

# State files
PHASE_FILE="$STATE_DIR/phase"
TASK_TYPE_FILE="$STATE_DIR/task-type"
PLAN_APPROVED_FILE="$STATE_DIR/plan-approved"
SUGGESTIONS_SHOWN_FILE="$STATE_DIR/suggestions-shown"
CURRENT_TURN_EDITS_FILE="$STATE_DIR/current-turn-edits"
WORKFLOW_INITIALIZED_FILE="$STATE_DIR/workflow-initialized"

# Auto-initialize workflow state with safe defaults
auto_init_state() {
    mkdir -p "$STATE_DIR"

    # Set safe defaults - assume feature task (strictest)
    echo "feature" > "$TASK_TYPE_FILE"
    echo "IMPLEMENT" > "$PHASE_FILE"
    echo "false" > "$PLAN_APPROVED_FILE"
    echo "false" > "$SUGGESTIONS_SHOWN_FILE"
    echo "0" > "$CURRENT_TURN_EDITS_FILE"
    echo "true" > "$WORKFLOW_INITIALIZED_FILE"

    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo -e "${CYAN}${BOLD}📋 AUTOWORKFLOW: STATE INITIALIZED${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    echo "Workflow state auto-initialized with safe defaults:"
    echo "  Task type:        feature (strictest)"
    echo "  Plan approved:    false"
    echo "  Suggestions shown: false"
    echo ""
}

# Check if workflow is initialized
is_workflow_initialized() {
    [ -d "$STATE_DIR" ] && [ -f "$WORKFLOW_INITIALIZED_FILE" ]
}

# Get current phase
get_phase() {
    if [ -f "$PHASE_FILE" ]; then
        cat "$PHASE_FILE"
    else
        echo "UNKNOWN"
    fi
}

# Get task type
get_task_type() {
    if [ -f "$TASK_TYPE_FILE" ]; then
        cat "$TASK_TYPE_FILE"
    else
        echo "feature"  # Default to strictest
    fi
}

# Check if plan is approved
is_plan_approved() {
    if [ -f "$PLAN_APPROVED_FILE" ]; then
        local status=$(cat "$PLAN_APPROVED_FILE")
        [ "$status" = "true" ] && return 0
    fi
    return 1
}

# Check if suggestions were shown
suggestions_shown() {
    if [ -f "$SUGGESTIONS_SHOWN_FILE" ]; then
        local status=$(cat "$SUGGESTIONS_SHOWN_FILE")
        [ "$status" = "true" ] && return 0
    fi
    return 1
}

# Get number of edits in current turn
get_turn_edit_count() {
    if [ -f "$CURRENT_TURN_EDITS_FILE" ]; then
        cat "$CURRENT_TURN_EDITS_FILE"
    else
        echo "0"
    fi
}

# Increment turn edit count
increment_turn_edits() {
    local current=$(get_turn_edit_count)
    local next=$((current + 1))
    echo "$next" > "$CURRENT_TURN_EDITS_FILE"
    echo "$next"
}

# Check if task type requires strict workflow
requires_strict_workflow() {
    local task_type="$1"
    case "$task_type" in
        # Strict workflow required
        feature|fix|refactor|perf|security|test)
            return 0
            ;;
        # Relaxed workflow
        docs|style|config)
            return 1
            ;;
        # Unknown = strict
        *)
            return 0
            ;;
    esac
}

# GATE 1: Plan Approval Check
check_plan_approval() {
    local task_type="$1"

    if ! requires_strict_workflow "$task_type"; then
        return 0  # Pass for relaxed task types
    fi

    if ! is_plan_approved; then
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo -e "${RED}${BOLD}⛔ GATE 1: PLAN APPROVAL REQUIRED${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo -e "${CYAN}Task Type:${NC}     $task_type"
        echo -e "${CYAN}Plan Approved:${NC} NO"
        echo ""
        echo "You MUST get user approval before making any edits."
        echo ""
        echo -e "${BOLD}Required steps:${NC}"
        echo "  1. Analyze the codebase"
        echo "  2. Present your plan to the user"
        echo "  3. Wait for explicit approval (yes/proceed/approved)"
        echo "  4. THEN implement"
        echo ""
        echo -e "${DIM}To mark approved: echo 'true' > $PLAN_APPROVED_FILE${NC}"
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        return 1
    fi
    return 0
}

# GATE 2: Suggestions Check (for feature tasks)
check_suggestions() {
    local task_type="$1"

    # Only enforce for feature tasks
    if [ "$task_type" != "feature" ]; then
        return 0
    fi

    if ! suggestions_shown; then
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo -e "${RED}${BOLD}⛔ GATE 2: SUGGESTIONS REQUIRED${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo -e "${CYAN}Task Type:${NC} feature"
        echo ""
        echo "For feature tasks, you MUST show 3-tier suggestions FIRST:"
        echo ""
        echo "  🔴 Required     - Must implement"
        echo "  🟡 Recommended  - Should implement"
        echo "  🟢 Optional     - Nice to have"
        echo ""
        echo "Show suggestions, let user select, THEN implement ONE at a time."
        echo ""
        echo -e "${DIM}To mark shown: echo 'true' > $SUGGESTIONS_SHOWN_FILE${NC}"
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        return 1
    fi
    return 0
}

# GATE 3: One Edit Per Turn Check (applies to ALL implementation)
check_one_edit_per_turn() {
    local task_type="$1"

    if ! requires_strict_workflow "$task_type"; then
        return 0  # Pass for relaxed task types
    fi

    local edit_count=$(get_turn_edit_count)

    if [ "$edit_count" -ge 1 ]; then
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo -e "${YELLOW}${BOLD}⛔ GATE 3: ONE EDIT PER TURN${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo -e "${CYAN}Edits this turn:${NC} $edit_count"
        echo ""
        echo "You can only make ONE edit per user turn."
        echo ""
        echo "This ensures:"
        echo "  1. Easier to track changes"
        echo "  2. Errors caught early"
        echo "  3. User can review incrementally"
        echo ""
        echo "Wait for user's next message before making another edit."
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        return 1
    fi

    return 0
}

# Main execution
main() {
    # STEP 1: Check if workflow is initialized
    if ! is_workflow_initialized; then
        # Auto-initialize with safe defaults
        auto_init_state

        # After init, BLOCK this edit attempt
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo -e "${RED}${BOLD}⛔ AUTOWORKFLOW: EDIT BLOCKED${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo "Workflow just initialized. Cannot edit yet."
        echo ""
        echo "You must first:"
        echo "  1. Show your analysis/plan to the user"
        echo "  2. Get user approval"
        echo "  3. For features: Show 3-tier suggestions"
        echo "  4. THEN implement one fix at a time"
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        exit 1
    fi

    # Get current state
    local task_type=$(get_task_type)
    local phase=$(get_phase)

    # STEP 2: Run all gates

    # GATE 1: Plan Approval
    if ! check_plan_approval "$task_type"; then
        exit 1
    fi

    # GATE 2: Suggestions (feature tasks only)
    if ! check_suggestions "$task_type"; then
        exit 1
    fi

    # GATE 3: One Edit Per Turn
    if ! check_one_edit_per_turn "$task_type"; then
        exit 1
    fi

    # ALL GATES PASSED - Allow edit and track it
    increment_turn_edits > /dev/null

    echo ""
    echo -e "${GREEN}✓${NC} Edit allowed (turn edit #$(get_turn_edit_count))"
    echo ""

    exit 0
}

main
