#!/bin/bash
# Template Version: 8 | ContextKit: 0.1.0 | Updated: 2025-09-24

# version-status.sh - ContextKit version management and project status
# Called by SessionStart hook when Claude Code starts a new session

# ⚠️ FOR DEVELOPERS: Do not edit this file - changes will be overwritten during ContextKit updates.
# Report bugs: https://github.com/FlineDev/ContextKit/issues

## Purpose
# - Auto-update global ContextKit installation via git pull on session startup
# - Check project/workspace ContextKit compatibility and suggest migration when needed
# - Only runs on startup sessions - silent for resume/clear/compact sessions
# - Supports --verbose flag for detailed migration reports

set -e

# Parse command line arguments
VERBOSE_MODE=false
if [ "$1" = "--verbose" ]; then
    VERBOSE_MODE=true
fi

# Parse session context from Claude Code hook JSON input
SESSION_SOURCE=$(jq -r '.source' 2>/dev/null || echo "startup")
PROJECT_DIR=${CLAUDE_PROJECT_DIR:-$(pwd)}
CONTEXTKIT_DIR="$HOME/.ContextKit"

# Only run on startup sessions - exit silently for all others (unless --verbose flag is used)
if [ "$SESSION_SOURCE" != "startup" ] && [ "$VERBOSE_MODE" = false ]; then
    exit 0
fi

if [ "$VERBOSE_MODE" = false ]; then
    echo "🧠 ContextKit: Checking for updates..."
fi


###########################################
# Global ContextKit Auto-Update
###########################################
update_global_contextkit() {
    # Check if ContextKit is installed globally
    if [ ! -d "$CONTEXTKIT_DIR" ]; then
        echo "  ❌ ContextKit not installed globally"
        echo "     💡 Install: curl -fsSL https://raw.githubusercontent.com/FlineDev/ContextKit/main/install.sh | sh"
        return 1
    fi

    # Get current version before update (line 2 parsing)
    local old_version="unknown"
    if [ -f "$CONTEXTKIT_DIR/CHANGELOG.md" ]; then
        old_version=$(sed -n '2p' "$CONTEXTKIT_DIR/CHANGELOG.md" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")
    fi

    # Auto-update global ContextKit repository
    cd "$CONTEXTKIT_DIR"
    if git pull origin main --quiet 2>/dev/null; then
        # Check if version actually changed (line 2 parsing)
        local new_version="unknown"
        if [ -f "$CONTEXTKIT_DIR/CHANGELOG.md" ]; then
            new_version=$(sed -n '2p' "$CONTEXTKIT_DIR/CHANGELOG.md" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")
        fi

        if [ "$old_version" != "$new_version" ] && [ "$new_version" != "unknown" ]; then
            echo "  🎉 ContextKit updated: v$old_version → v$new_version"
            echo "     💡 Update your project templates: /ctxk:proj:migrate"
            return 0
        else
            echo "  ✅ ContextKit: Up to date (v$new_version)"
            return 0
        fi
    else
        echo "  ⚠️  Could not check for updates (no internet connection)"
        echo "     ✅ Using cached version: v$old_version"
        return 0
    fi
}

###########################################
# Project Compatibility Check
###########################################
check_project_compatibility() {
    cd "$PROJECT_DIR"

    # Get current global version from CHANGELOG.md (line 2 parsing)
    local global_version="unknown"
    if [ -f "$CONTEXTKIT_DIR/CHANGELOG.md" ]; then
        global_version=$(sed -n '2p' "$CONTEXTKIT_DIR/CHANGELOG.md" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")
    fi

    # Check project version from installed plan command
    if [ -f ".claude/commands/ctxk/plan/1-spec.md" ]; then
        local project_version=$(sed -n '2p' ".claude/commands/ctxk/plan/1-spec.md" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")

        if [ "$project_version" != "$global_version" ] && [ "$project_version" != "unknown" ] && [ "$global_version" != "unknown" ]; then
            echo "  ⚠️  Updates available: v$project_version → v$global_version"
            echo "     💡 Run: /ctxk:proj:migrate when ready"
            return 1
        fi
    else
        echo "  ⚪ Project not initialized with ContextKit"
        echo "     💡 Run: /ctxk:proj:init"
        return 1
    fi

    # Check workspace compatibility (find workspace Context.md in parent directories)
    check_workspace_compatibility "$global_version"
}

check_workspace_compatibility() {
    local global_version="$1"
    local current_dir="$PROJECT_DIR"

    while [ "$current_dir" != "/" ]; do
        local parent_dir="$(dirname "$current_dir")"
        if [ -f "$parent_dir/Context.md" ] && [ "$parent_dir" != "$PROJECT_DIR" ]; then
            if grep -q "ContextKit Version" "$parent_dir/Context.md"; then
                local workspace_version=$(grep "ContextKit Version" "$parent_dir/Context.md" | sed 's/.*: \(.*\)/\1/' 2>/dev/null || echo "unknown")

                if [ "$workspace_version" != "$global_version" ] && [ "$workspace_version" != "unknown" ]; then
                    echo "  ⚠️  Workspace needs update: v$workspace_version → v$global_version"
                    echo "     💡 Update: /ctxk:proj:init-workspace (in workspace directory)"
                    return 1
                fi
            fi
            break
        fi
        current_dir="$parent_dir"
    done
    return 0
}

###########################################
# Template Update Check (Lightweight)
###########################################
check_template_updates() {
    cd "$PROJECT_DIR"

    local updates_needed=0

    # Check both local project templates AND global proj commands
    local project_dirs=(
        "$HOME/.claude/commands/ctxk/proj"
        ".claude/commands/ctxk/plan"
        ".claude/commands/ctxk/impl"
        ".claude/commands/ctxk/bckl"
        ".claude/agents/ctxk"
        "Context/Scripts"
    )

    local source_dirs=(
        "$CONTEXTKIT_DIR/Templates/Commands/proj"
        "$CONTEXTKIT_DIR/Templates/Commands/plan"
        "$CONTEXTKIT_DIR/Templates/Commands/impl"
        "$CONTEXTKIT_DIR/Templates/Commands/bckl"
        "$CONTEXTKIT_DIR/Templates/Agents"
        "$CONTEXTKIT_DIR/Templates/Scripts"
    )

    for i in "${!project_dirs[@]}"; do
        local local_dir="${project_dirs[i]}"
        local source_dir="${source_dirs[i]}"

        if [ -d "$local_dir" ] && [ -d "$source_dir" ]; then
            local outdated=$(count_outdated_templates "$local_dir" "$source_dir")
            updates_needed=$((updates_needed + outdated))
        fi
    done

    # Check guidelines separately - only guidelines that exist in project
    if [ -d "Context/Guidelines" ]; then
        local guidelines_outdated=$(check_project_guidelines_updates)
        updates_needed=$((updates_needed + guidelines_outdated))
    fi

    if [ "$updates_needed" -gt 0 ]; then
        echo "  ⚠️  Project template updates available: $updates_needed files"
        echo "     💡 Run: /ctxk:proj:migrate to update"
        return 1
    fi
    return 0
}

count_outdated_templates() {
    local local_dir="$1"
    local source_dir="$2"
    local count=0

    if [ ! -d "$local_dir" ] || [ ! -d "$source_dir" ]; then
        echo "0"
        return
    fi

    # Compare template versions AND ContextKit versions for existing files
    for local_file in "$local_dir"/*.md "$local_dir"/*.sh; do
        [ -f "$local_file" ] || continue

        local rel_path="${local_file#$local_dir/}"
        local source_file="$source_dir/$rel_path"

        if [ -f "$source_file" ]; then
            local local_template_version=$(sed -n '2p' "$local_file" 2>/dev/null | grep -o "Template Version: [0-9]*" | grep -o "[0-9]*" || echo "0")
            local source_template_version=$(sed -n '2p' "$source_file" 2>/dev/null | grep -o "Template Version: [0-9]*" | grep -o "[0-9]*" || echo "0")

            local local_contextkit_version=$(sed -n '2p' "$local_file" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")
            local source_contextkit_version=$(sed -n '2p' "$source_file" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")

            # File is outdated if template version is lower OR ContextKit version differs
            local is_outdated=false
            if [ "$local_template_version" -lt "$source_template_version" ] 2>/dev/null; then
                is_outdated=true
            elif [ "$local_contextkit_version" != "$source_contextkit_version" ] && [ "$local_contextkit_version" != "unknown" ] && [ "$source_contextkit_version" != "unknown" ]; then
                is_outdated=true
            fi

            if [ "$is_outdated" = true ]; then
                count=$((count + 1))
                if [ "$VERBOSE_MODE" = true ]; then
                    echo "OUTDATED:$source_file:$local_file" >&2
                fi
            fi
        fi
    done

    # Check for new files in source directory (files that don't exist locally yet)
    for source_file in "$source_dir"/*.md "$source_dir"/*.sh; do
        [ -f "$source_file" ] || continue

        local rel_path="${source_file#$source_dir/}"
        local local_file="$local_dir/$rel_path"

        if [ ! -f "$local_file" ]; then
            # New file that doesn't exist in local directory
            count=$((count + 1))
            if [ "$VERBOSE_MODE" = true ]; then
                echo "NEW:$source_file:$local_file" >&2
            fi
        fi
    done

    echo "$count"
}

check_project_guidelines_updates() {
    local count=0

    if [ ! -d "Context/Guidelines" ]; then
        echo "0"
        return
    fi

    # Only check guidelines that exist in project
    for project_guideline in Context/Guidelines/*.md; do
        [ -f "$project_guideline" ] || continue

        local guideline_name=$(basename "$project_guideline")
        local source_guideline="$CONTEXTKIT_DIR/Templates/Guidelines/$guideline_name"

        if [ -f "$source_guideline" ]; then
            local project_template_version=$(sed -n '2p' "$project_guideline" 2>/dev/null | grep -o "Template Version: [0-9]*" | grep -o "[0-9]*" || echo "0")
            local source_template_version=$(sed -n '2p' "$source_guideline" 2>/dev/null | grep -o "Template Version: [0-9]*" | grep -o "[0-9]*" || echo "0")

            local project_contextkit_version=$(sed -n '2p' "$project_guideline" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")
            local source_contextkit_version=$(sed -n '2p' "$source_guideline" 2>/dev/null | grep -o "ContextKit: [^|]*" | sed 's/ContextKit: *//' | sed 's/ *$//' || echo "unknown")

            # File is outdated if template version is lower OR ContextKit version differs
            local is_outdated=false
            if [ "$project_template_version" -lt "$source_template_version" ] 2>/dev/null; then
                is_outdated=true
            elif [ "$project_contextkit_version" != "$source_contextkit_version" ] && [ "$project_contextkit_version" != "unknown" ] && [ "$source_contextkit_version" != "unknown" ]; then
                is_outdated=true
            fi

            if [ "$is_outdated" = true ]; then
                count=$((count + 1))
                if [ "$VERBOSE_MODE" = true ]; then
                    echo "OUTDATED:$source_guideline:$project_guideline" >&2
                fi
            fi
        fi
    done

    echo "$count"
}

###########################################
# Main Execution
###########################################
main() {
    local needs_updates=0

    # Auto-update global ContextKit and check for changes
    if ! update_global_contextkit; then
        return 1
    fi

    # Check project and workspace compatibility
    if ! check_project_compatibility; then
        needs_updates=1
    fi

    # Check if template updates are available
    if ! check_template_updates; then
        needs_updates=1
    fi

    # Simple ready message when everything is up-to-date
    if [ "$needs_updates" -eq 0 ]; then
        echo "  🧠 ContextKit ready for this session"
    fi
}

# Execute main function
main "$@"