#!/bin/bash
# AutoWorkflow Session Check Hook
# Runs on: UserPromptSubmit (every user message)
# Purpose: Initialize state, check for missing files, route tasks
#
# This hook implements:
# - on:conversation_start trigger
# - on:blueprint_missing trigger (prompt user for documentation)
# - on:init_needed trigger
# - on:task_received trigger (task classification)

# 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:-.}"

# Source the logger
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/logger.sh" 2>/dev/null || true

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

# State files
SESSION_FILE="$STATE_DIR/session-id"
PHASE_FILE="$STATE_DIR/phase"
TASK_TYPE_FILE="$STATE_DIR/task-type"
BLUEPRINT_CHECK_FILE="$STATE_DIR/blueprint-checked"
TASK_DESCRIPTION_FILE="$STATE_DIR/task-description"
PLAN_APPROVED_FILE="$STATE_DIR/plan-approved"
CHANGED_FILES_FILE="$STATE_DIR/changed-files"
SESSION_RESUMED_FILE="$STATE_DIR/session-resumed"
CURRENT_TURN_EDITS_FILE="$STATE_DIR/current-turn-edits"
SUGGESTIONS_SHOWN_FILE="$STATE_DIR/suggestions-shown"

# Memory system (Serena-inspired)
MEMORY_DIR="$STATE_DIR/memories"
CONTEXT_FILE="$MEMORY_DIR/context.md"

# Load previous context if available (Serena-inspired)
load_previous_context() {
    if [ -f "$CONTEXT_FILE" ]; then
        echo ""
        echo -e "${CYAN}━━━ PREVIOUS SESSION CONTEXT ━━━${NC}"
        echo ""
        # Extract key sections from context file
        if grep -q "## What Was Done" "$CONTEXT_FILE"; then
            echo -e "${BOLD}What Was Done:${NC}"
            sed -n '/## What Was Done/,/## /p' "$CONTEXT_FILE" | head -10 | tail -n +2
            echo ""
        fi
        if grep -q "## What Remains" "$CONTEXT_FILE"; then
            echo -e "${BOLD}What Remains:${NC}"
            sed -n '/## What Remains/,/## /p' "$CONTEXT_FILE" | head -10 | tail -n +2
            echo ""
        fi
        if grep -q "## Key Decisions Made" "$CONTEXT_FILE"; then
            echo -e "${BOLD}Key Decisions:${NC}"
            sed -n '/## Key Decisions Made/,/## /p' "$CONTEXT_FILE" | head -5 | tail -n +2
            echo ""
        fi
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo ""
        echo -e "${DIM}Full context: .claude/.autoworkflow/memories/context.md${NC}"
        echo ""
        return 0
    fi
    return 1
}

# Check for resumable session state
check_session_resume() {
    # Only show resume prompt once per session
    if [ -f "$SESSION_RESUMED_FILE" ]; then
        return 1
    fi

    # Check if there's a previous session with active state
    if [ -f "$PHASE_FILE" ]; then
        local phase=$(cat "$PHASE_FILE")

        # Only prompt for non-idle, non-complete states
        if [ "$phase" != "IDLE" ] && [ "$phase" != "" ] && [ "$phase" != "COMMIT" ]; then
            local task_type=""
            local verify_iter="0"
            local plan_approved="false"
            local changed_count="0"

            [ -f "$TASK_TYPE_FILE" ] && task_type=$(cat "$TASK_TYPE_FILE")
            [ -f "$STATE_DIR/verify-iteration" ] && verify_iter=$(cat "$STATE_DIR/verify-iteration")
            [ -f "$PLAN_APPROVED_FILE" ] && plan_approved=$(cat "$PLAN_APPROVED_FILE")
            [ -f "$CHANGED_FILES_FILE" ] && changed_count=$(wc -l < "$CHANGED_FILES_FILE" 2>/dev/null | tr -d ' ')

            echo ""
            echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            echo -e "${CYAN}${BOLD}📍 AUTOWORKFLOW: SESSION RESUME${NC}"
            echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            echo ""
            echo -e "${BOLD}Previous session state detected:${NC}"
            echo ""
            echo -e "  ${CYAN}Phase:${NC}           $phase"
            [ -n "$task_type" ] && echo -e "  ${CYAN}Task type:${NC}       $task_type"
            echo -e "  ${CYAN}Plan approved:${NC}   $plan_approved"
            echo -e "  ${CYAN}Verify attempts:${NC} $verify_iter/10"
            [ "$changed_count" -gt 0 ] 2>/dev/null && echo -e "  ${CYAN}Changed files:${NC}   $changed_count"
            echo ""

            # Show changed files if any
            if [ -f "$CHANGED_FILES_FILE" ] && [ "$changed_count" -gt 0 ] 2>/dev/null; then
                echo -e "${DIM}Pending changes:${NC}"
                head -5 "$CHANGED_FILES_FILE" | while read file; do
                    echo -e "  ${DIM}- $file${NC}"
                done
                [ "$changed_count" -gt 5 ] 2>/dev/null && echo -e "  ${DIM}... and $((changed_count - 5)) more${NC}"
                echo ""
            fi

            # Show workflow position
            local workflow=$(get_workflow "$task_type")
            echo -e "${DIM}Workflow: $workflow${NC}"
            echo -e "${DIM}          ↑ Current: $phase${NC}"
            echo ""

            echo "Continue from $phase phase, or start fresh?"
            echo ""
            echo -e "${DIM}(Say 'continue' to resume, or describe new task to start fresh)${NC}"
            echo ""
            echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            echo ""

            # Load previous context if available
            load_previous_context

            # Mark that we've shown the resume prompt
            touch "$SESSION_RESUMED_FILE"
            return 0
        fi
    fi

    return 1
}

# Generate session ID if new session
init_session() {
    if [ ! -f "$SESSION_FILE" ]; then
        echo "$(date +%s)-$$" > "$SESSION_FILE"
        echo "IDLE" > "$PHASE_FILE"
        rm -f "$STATE_DIR/verify-iteration" 2>/dev/null
        rm -f "$STATE_DIR/verify-status" 2>/dev/null
        rm -f "$STATE_DIR/changed-files" 2>/dev/null
        rm -f "$BLUEPRINT_CHECK_FILE" 2>/dev/null
        rm -f "$TASK_TYPE_FILE" 2>/dev/null
        rm -f "$PLAN_APPROVED_FILE" 2>/dev/null
        rm -f "$SESSION_RESUMED_FILE" 2>/dev/null
        return 0  # New session
    fi
    return 1  # Existing session
}

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

# Set phase
set_phase() {
    echo "$1" > "$PHASE_FILE"
}

# Check if autoworkflow package is installed but not initialized
check_init_needed() {
    if [ -d "node_modules/autoworkflow" ] && [ ! -f "CLAUDE.md" ]; then
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo -e "${YELLOW}${BOLD}📦 AUTOWORKFLOW: INIT NEEDED${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo "AutoWorkflow package detected but not initialized."
        echo ""
        echo "Run: npx autoworkflow init"
        echo ""
        echo "This will create:"
        echo "  - CLAUDE.md (entry point)"
        echo "  - system/ (triggers, loops, gates)"
        echo "  - instructions/ (workflow, rules, blueprint)"
        echo "  - .claude/ (commands, hooks)"
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        return 0
    fi
    return 1
}

# Check for project documentation - ask user to provide their docs
check_blueprint() {
    # Only check once per session
    if [ -f "$BLUEPRINT_CHECK_FILE" ]; then
        return 0
    fi

    # Mark as checked
    touch "$BLUEPRINT_CHECK_FILE"

    if [ ! -f "instructions/BLUEPRINT.md" ]; then
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo -e "${YELLOW}${BOLD}📋 AUTOWORKFLOW: PROJECT DOCUMENTATION NEEDED${NC}"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""
        echo "No project documentation found."
        echo ""
        echo -e "${BOLD}Please provide your project documentation:${NC}"
        echo ""
        echo "  ${CYAN}Option 1:${NC} Point to existing docs"
        echo "    • PRD (Product Requirements Document)"
        echo "    • Specification document"
        echo "    • Userflow document"
        echo "    • Implementation guide"
        echo "    • Any design/architecture docs"
        echo ""
        echo "  ${CYAN}Option 2:${NC} Describe your project"
        echo "    • What does this project do?"
        echo "    • What are the main features?"
        echo "    • What's the tech stack?"
        echo ""
        echo "  ${CYAN}Option 3:${NC} Interactive"
        echo "    • Say: \"Help me define my project\""
        echo "    • I'll ask questions to understand your project"
        echo ""
        echo -e "${DIM}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo ""
        echo -e "${BOLD}When you provide documentation:${NC}"
        echo ""
        echo "  Your document = ${GREEN}SINGLE SOURCE OF TRUTH${NC}"
        echo ""
        echo "  • I will read and understand it"
        echo "  • I will reference it for all tasks"
        echo "  • No transformation or format conversion"
        echo ""
        echo -e "${DIM}Your document structure is preserved exactly as-is.${NC}"
        echo -e "${DIM}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo ""
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
        echo ""

        # Set phase to indicate documentation is needed
        set_phase "DOCS_REQUIRED"
        return 1
    fi

    # Also check for AI_RULES.md
    if [ ! -f "instructions/AI_RULES.md" ]; then
        echo ""
        echo -e "${YELLOW}⚠${NC}  instructions/AI_RULES.md is missing."
        echo "    Generate it during the project audit."
        echo ""
    fi

    return 0
}

# Classify task type from user input
classify_task() {
    local input="$1"
    local input_lower=$(echo "$input" | tr '[:upper:]' '[:lower:]')

    # Query patterns (questions, not actions)
    if echo "$input_lower" | grep -qE "^(what|how|why|where|when|which|who|can you|could you|explain|show me|find|search|list|tell me)"; then
        echo "query"
        return
    fi

    # Feature patterns
    if echo "$input_lower" | grep -qE "(add|create|implement|build|new|feature|functionality|capability)"; then
        echo "feature"
        return
    fi

    # Fix patterns
    if echo "$input_lower" | grep -qE "(fix|bug|broken|doesn't work|error|issue|problem|wrong|crash|fail)"; then
        echo "fix"
        return
    fi

    # Refactor patterns
    if echo "$input_lower" | grep -qE "(refactor|clean up|restructure|reorganize|extract|split|merge|rename|improve)"; then
        echo "refactor"
        return
    fi

    # Style patterns
    if echo "$input_lower" | grep -qE "(style|css|color|layout|design|spacing|font|responsive|mobile|ui|ux)"; then
        echo "style"
        return
    fi

    # Docs patterns
    if echo "$input_lower" | grep -qE "(document|readme|comment|jsdoc|explain|describe)"; then
        echo "docs"
        return
    fi

    # Test patterns
    if echo "$input_lower" | grep -qE "(test|spec|coverage|unit test|integration|e2e)"; then
        echo "test"
        return
    fi

    # Performance patterns
    if echo "$input_lower" | grep -qE "(performance|optimize|speed|fast|slow|lag|memory|bundle)"; then
        echo "perf"
        return
    fi

    # Security patterns
    if echo "$input_lower" | grep -qE "(security|vulnerability|auth|permission|sanitize|validate|escape|encrypt)"; then
        echo "security"
        return
    fi

    # Config patterns
    if echo "$input_lower" | grep -qE "(config|setting|environment|env|setup|install|dependency)"; then
        echo "config"
        return
    fi

    # Default to feature for most actionable requests
    echo "feature"
}

# Get workflow for task type
get_workflow() {
    local task_type="$1"

    case "$task_type" in
        feature)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → AUDIT → COMMIT → UPDATE"
            ;;
        fix)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → COMMIT"
            ;;
        refactor)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → AUDIT → COMMIT"
            ;;
        style|docs|config)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → COMMIT"
            ;;
        test)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → RUN_TESTS → COMMIT"
            ;;
        perf)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → AUDIT → COMMIT"
            ;;
        security)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → SECURITY_REVIEW → COMMIT"
            ;;
        query)
            echo "ANALYZE → RESPOND"
            ;;
        *)
            echo "ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → COMMIT"
            ;;
    esac
}

# Check if task requires audit
requires_audit() {
    local task_type="$1"
    case "$task_type" in
        feature|refactor|perf)
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

# Output task classification
output_classification() {
    local task_type="$1"
    local workflow=$(get_workflow "$task_type")

    # Save task type to state
    echo "$task_type" > "$TASK_TYPE_FILE"
    set_phase "ANALYZE"

    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo -e "${BOLD}AUTOWORKFLOW: TASK CLASSIFIED${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    echo -e "${CYAN}Type:${NC}     $task_type"
    echo -e "${CYAN}Workflow:${NC} $workflow"
    echo ""

    # Show required gates
    echo -e "${CYAN}Required Gates:${NC}"
    echo "  ☐ plan_approval_gate (user must approve)"
    echo "  ☐ verify_gate (typecheck + lint)"

    if requires_audit "$task_type"; then
        echo "  ☐ audit_gate (UI enforcement + cycles)"
    fi

    echo "  ☐ pre_commit_gate (all checks)"
    echo ""

    # Show current phase
    echo -e "${CYAN}Current Phase:${NC} ANALYZE"
    echo ""

    # Instructions for this phase
    echo -e "${DIM}Read relevant files and understand the codebase.${NC}"
    echo -e "${DIM}Reference user's documentation for requirements.${NC}"
    echo ""
    echo -e "${DIM}💡 Tip: Use 'phase-transition.sh memory-save decisions <key> <value>' to record decisions.${NC}"
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
}

# Show current workflow state
show_state() {
    local phase=$(get_phase)
    local task_type=""

    if [ -f "$TASK_TYPE_FILE" ]; then
        task_type=$(cat "$TASK_TYPE_FILE")
    fi

    if [ "$phase" != "IDLE" ] && [ -n "$task_type" ]; then
        echo ""
        echo -e "${DIM}━━━ Workflow State ━━━${NC}"
        echo -e "${DIM}Phase: $phase | Task: $task_type${NC}"

        # Show verify iteration if in verify/fix
        if [ "$phase" = "VERIFY" ] || [ "$phase" = "FIX" ]; then
            if [ -f "$STATE_DIR/verify-iteration" ]; then
                local iteration=$(cat "$STATE_DIR/verify-iteration")
                echo -e "${DIM}Verify iteration: $iteration/10${NC}"
            fi
        fi

        echo -e "${DIM}━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo ""
    fi
}

# Reset turn-based state (called each user turn)
reset_turn_state() {
    # Reset edit counter for this turn
    echo "0" > "$CURRENT_TURN_EDITS_FILE"
}

# Load and display memories summary (for context awareness)
show_memories_summary() {
    local has_memories=false

    # Check if any memories exist (beyond templates)
    for file in "$MEMORY_DIR/decisions.md" "$MEMORY_DIR/patterns.md" "$MEMORY_DIR/blockers.md"; do
        if [ -f "$file" ]; then
            local count=$(grep -c "^## " "$file" 2>/dev/null || echo "0")
            if [ "$count" -gt 1 ]; then
                has_memories=true
                break
            fi
        fi
    done

    if [ "$has_memories" = true ]; then
        echo ""
        echo -e "${CYAN}━━━ PROJECT MEMORIES ━━━${NC}"

        if [ -f "$MEMORY_DIR/decisions.md" ]; then
            local count=$(grep -c "^## " "$MEMORY_DIR/decisions.md" 2>/dev/null || echo "0")
            [ "$count" -gt 1 ] && echo -e "  ${GREEN}●${NC} Decisions: $((count - 1)) recorded"
        fi

        if [ -f "$MEMORY_DIR/patterns.md" ]; then
            local count=$(grep -c "^## " "$MEMORY_DIR/patterns.md" 2>/dev/null || echo "0")
            [ "$count" -gt 1 ] && echo -e "  ${GREEN}●${NC} Patterns: $((count - 1)) recorded"
        fi

        if [ -f "$MEMORY_DIR/blockers.md" ]; then
            local count=$(grep -c "^## " "$MEMORY_DIR/blockers.md" 2>/dev/null || echo "0")
            [ "$count" -gt 1 ] && echo -e "  ${YELLOW}●${NC} Blockers: $((count - 1)) recorded"
        fi

        echo ""
        echo -e "${DIM}Read: .claude/.autoworkflow/memories/*.md${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo ""
    fi
}

# Main execution
main() {
    aw_log_hook "session-check.sh" "START"

    local is_new_session=false

    # Initialize session
    if init_session; then
        is_new_session=true
        aw_log "HOOK" "session-check.sh" "NEW_SESSION"
    fi

    # Reset turn state on each user message
    reset_turn_state

    # Check if init is needed (package installed but not set up)
    if check_init_needed; then
        aw_log "HOOK" "session-check.sh" "INIT_NEEDED"
        exit 0
    fi

    # Check for session resume (only on existing sessions)
    if [ "$is_new_session" = false ]; then
        check_session_resume
    fi

    # Check for missing blueprint (prompts user for documentation)
    if ! check_blueprint; then
        aw_log "HOOK" "session-check.sh" "DOCS_REQUIRED"
    fi

    # Show memories summary (if any exist)
    show_memories_summary

    # Show current state if not idle
    show_state

    aw_log_hook "session-check.sh" "COMPLETE"
}

main
