#!/bin/sh

# SuperClaude - AI-powered development toolkit
# Usage: ./scripts/superclaude.sh <command> [flags]

# Get version from package.json
get_version() {
    local script_dir="$(dirname "$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")")"
    local package_json="$script_dir/../package.json"
    
    # Try to find package.json in various locations
    if [ -f "$package_json" ]; then
        grep '"version"' "$package_json" | head -1 | sed 's/.*"version": *"\([^"]*\)".*/\1/'
    elif [ -f "./package.json" ]; then
        grep '"version"' "./package.json" | head -1 | sed 's/.*"version": *"\([^"]*\)".*/\1/'
    elif command -v npm >/dev/null 2>&1; then
        npm list -g superclaude --depth=0 2>/dev/null | grep superclaude | sed 's/.*@\([0-9][^[:space:]]*\).*/\1/' || echo "unknown"
    else
        echo "unknown"
    fi
}

SUPERCLAUDE_VERSION=$(get_version)

# Get script directory for finding prompt files
get_script_dir() {
    dirname "$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"
}

# Load and process prompt template
load_prompt() {
    local prompt_name="$1"
    local script_dir="$(get_script_dir)"
    local prompt_file="$script_dir/../prompts/$prompt_name.md"
    
    if [ -f "$prompt_file" ]; then
        cat "$prompt_file"
    else
        print_error "Prompt file not found: $prompt_file"
        exit 1
    fi
}

# Simple template variable replacement
process_template() {
    local template="$1"
    local key="$2"
    local value="$3"
    
    # For now, just replace the first occurrence manually
    # This is a simple implementation that works for our basic use case
    printf "%s" "$template" | sed "s/{{$key}}/PLACEHOLDER_START/g" | \
    while IFS= read -r line; do
        if [[ "$line" == *"PLACEHOLDER_START"* ]]; then
            echo "${line/PLACEHOLDER_START/$value}"
        else
            echo "$line"
        fi
    done
}

# Parse flags and command
INTERACTIVE_MODE=false
VERBOSE_MODE=false
COMMAND=""
COMMIT_GUIDANCE=""

while [ $# -gt 0 ]; do
    case $1 in
        --interactive|-i)
            INTERACTIVE_MODE=true
            shift
            ;;
        --verbose|-v)
            VERBOSE_MODE=true
            shift
            ;;
        --version)
            COMMAND="version"
            shift
            ;;
        --verify)
            COMMAND="verify"
            shift
            ;;
        -*)
            echo "❌ Unknown flag: $1"
            echo "Available flags: --interactive/-i, --verbose/-v, --verify, --version"
            exit 1
            ;;
        *)
            if [ -z "$COMMAND" ]; then
                COMMAND="$1"
            elif [ "$COMMAND" = "commit" ] && [ -z "$COMMIT_GUIDANCE" ]; then
                # Capture commit guidance message for commit command
                COMMIT_GUIDANCE="$1"
            fi
            shift
            ;;
    esac
done

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# Helper functions
print_header() {
    printf "${PURPLE}🔮 SuperClaude - %s${NC}\n" "$1"
}

print_step() {
    printf "${BLUE}%s${NC}\n" "$1"
}

print_substep() {
    if [ "$VERBOSE_MODE" = true ]; then
        printf "${BLUE}  ├─ %s${NC}\n" "$1"
    fi
}

print_thinking() {
    if [ "$VERBOSE_MODE" = true ]; then
        printf "${YELLOW}🧠 Claude thinking: %s${NC}\n" "$1"
    fi
}

print_progress() {
    printf "${BLUE}⏳ %s${NC}\n" "$1"
}

print_success() {
    printf "${GREEN}✅ %s${NC}\n" "$1"
}

print_error() {
    printf "${RED}❌ %s${NC}\n" "$1"
}

print_verbose() {
    if [ "$VERBOSE_MODE" = true ]; then
        printf "${BLUE}  └─ %s${NC}\n" "$1"
    fi
}

# Check if we're in a git repo
check_git_repo() {
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        print_error "Not in a git repository!"
        exit 1
    fi
}

# Cache file for dependency verification
CACHE_FILE="$HOME/.superclaude/cache.json"
CACHE_EXPIRY_HOURS=24

# Create cache directory if it doesn't exist
ensure_cache_dir() {
    mkdir -p "$(dirname "$CACHE_FILE")"
}

# Check if cache is valid (exists and not expired)
is_cache_valid() {
    if [ ! -f "$CACHE_FILE" ]; then
        return 1
    fi
    
    local cache_time=$(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null)
    local current_time=$(date +%s)
    local expiry_seconds=$((CACHE_EXPIRY_HOURS * 3600))
    
    if [ $((current_time - cache_time)) -gt $expiry_seconds ]; then
        return 1
    fi
    
    return 0
}

# Save successful verification to cache
save_cache() {
    ensure_cache_dir
    cat > "$CACHE_FILE" << EOF
{
  "last_check": "$(date -Iseconds)",
  "status": "verified",
  "claude_version": "$(claude --version 2>/dev/null | head -1)",
  "git_version": "$(git --version)",
  "node_version": "$(node --version)",
  "global_auth": true,
  "auth_method": "$1"
}
EOF
}

# Quick dependency check (only essentials)
quick_check() {
    # Only check Claude and current repo auth
    if ! command -v claude >/dev/null 2>&1; then
        return 1
    fi
    
    # This Claude authentication test can take a few seconds
    if ! claude --print "test" >/dev/null 2>&1; then
        return 1
    fi
    
    # Check GitHub authentication globally (not per-repo)
    # This checks if user has global GitHub access, not specific to current repo
    if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
        # GitHub CLI is authenticated globally
        return 0
    elif ssh -T git@github.com 2>&1 | grep -q "successfully authenticated"; then
        # SSH key is working globally for GitHub
        return 0
    else
        # No global GitHub authentication found
        return 1
    fi
    
    return 0
}

# Check for updates (cached for 24 hours)
check_for_updates() {
    local update_cache_file="$HOME/.superclaude/update_cache.json"
    
    # Check if update cache is valid (24 hours)
    if [ -f "$update_cache_file" ]; then
        local cache_time=$(stat -f %m "$update_cache_file" 2>/dev/null || stat -c %Y "$update_cache_file" 2>/dev/null)
        local current_time=$(date +%s)
        local expiry_seconds=$((24 * 3600))
        
        if [ $((current_time - cache_time)) -lt $expiry_seconds ]; then
            # Use cached result
            if [ -f "$update_cache_file" ] && grep -q "update_available.*true" "$update_cache_file"; then
                local latest_version=$(grep '"latest_version"' "$update_cache_file" | sed 's/.*"latest_version": *"\([^"]*\)".*/\1/')
                show_update_notification "$latest_version"
            fi
            return 0
        fi
    fi
    
    # Check npm for latest version (async, don't block if it fails)
    print_thinking "Checking for SuperClaude updates..."
    
    # Use timeout to prevent hanging
    local latest_version=""
    if command -v timeout >/dev/null 2>&1; then
        latest_version=$(timeout 3s npm view superclaude version 2>/dev/null || echo "")
    else
        # Fallback for systems without timeout
        latest_version=$(npm view superclaude version 2>/dev/null || echo "")
    fi
    
    ensure_cache_dir
    
    if [ -n "$latest_version" ] && [ "$latest_version" != "$SUPERCLAUDE_VERSION" ]; then
        # Update available
        cat > "$update_cache_file" << EOF
{
  "last_check": "$(date -Iseconds)",
  "current_version": "$SUPERCLAUDE_VERSION",
  "latest_version": "$latest_version",
  "update_available": true
}
EOF
        show_update_notification "$latest_version"
    else
        # No update or failed to check
        cat > "$update_cache_file" << EOF
{
  "last_check": "$(date -Iseconds)",
  "current_version": "$SUPERCLAUDE_VERSION",
  "latest_version": "${latest_version:-unknown}",
  "update_available": false
}
EOF
    fi
}

# Show update notification
show_update_notification() {
    local latest_version="$1"
    printf "${YELLOW}📦 Update Available!${NC}\n"
    printf "${YELLOW}  ├─ Current version: ${SUPERCLAUDE_VERSION}${NC}\n"
    printf "${YELLOW}  ├─ Latest version:  ${latest_version}${NC}\n"
    printf "${YELLOW}  └─ Update command:  ${GREEN}npm install -g superclaude@latest${NC}\n"
    echo ""
}

# Check system dependencies (with smart caching)
check_dependencies() {
    # Force full check if --verify flag is used
    if [[ "$*" == *"--verify"* ]]; then
        print_verbose "🔄 Forcing full dependency verification (--verify flag)"
    elif is_cache_valid; then
        print_substep "Testing Claude AI authentication..."
        if quick_check; then
            if [ "$VERBOSE_MODE" = true ]; then
                local cache_age=$(( ($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null)) / 3600 ))
                print_verbose "✅ Dependencies verified (cached ${cache_age}h ago)"
            else
                print_verbose "✅ Dependencies verified (cached)"
            fi
            return 0
        else
            print_substep "Cache invalid or authentication failed, running full verification..."
        fi
    else
        print_substep "Running dependency verification (this may take a few seconds)..."
    fi
    
    print_step "🔧 System dependencies check..."
    print_substep "Verifying required tools are installed..."
    
    local missing_deps=()
    local all_good=true
    local auth_method=""
    
    # Check Claude Code
    print_thinking "Checking Claude Code availability..."
    if command -v claude >/dev/null 2>&1; then
        local claude_version=$(claude --version 2>/dev/null || echo "unknown")
        print_verbose "✓ Claude Code found (version: $claude_version)"
        
        # Check Claude Code authentication by testing actual API call
        print_thinking "Verifying Claude Code authentication..."
        if claude --print "Hello, testing authentication" >/dev/null 2>&1; then
            print_verbose "✓ Claude Code authentication working"
        else
            print_error "✗ Claude Code not authenticated"
            print_verbose "  Run 'claude' and complete the authentication process"
            missing_deps+=("claude-authentication")
            all_good=false
        fi
    else
        print_error "✗ Claude Code not found"
        missing_deps+=("claude")
        all_good=false
    fi
    
    # Check Git
    print_thinking "Checking Git installation..."
    if command -v git >/dev/null 2>&1; then
        local git_version=$(git --version | cut -d' ' -f3)
        print_verbose "✓ Git found (version: $git_version)"
        
        # Check Git configuration
        print_thinking "Verifying Git user configuration..."
        local git_user_name=$(git config --global user.name 2>/dev/null)
        local git_user_email=$(git config --global user.email 2>/dev/null)
        
        if [ -n "$git_user_name" ] && [ -n "$git_user_email" ]; then
            print_verbose "✓ Git configured (${git_user_name} <${git_user_email}>)"
        else
            print_error "✗ Git user not configured"
            missing_deps+=("git-config")
            all_good=false
        fi
    else
        print_error "✗ Git not found"
        missing_deps+=("git")
        all_good=false
    fi
    
    # Check Node.js
    print_thinking "Checking Node.js installation..."
    if command -v node >/dev/null 2>&1; then
        local node_version=$(node --version)
        print_verbose "✓ Node.js found (version: $node_version)"
    else
        print_error "✗ Node.js not found"
        missing_deps+=("node")
        all_good=false
    fi
    
    # Check Yarn (optional but recommended)
    print_thinking "Checking Yarn package manager..."
    if command -v yarn >/dev/null 2>&1; then
        local yarn_version=$(yarn --version)
        print_verbose "✓ Yarn found (version: $yarn_version)"
    else
        print_verbose "⚠ Yarn not found (optional, npm can be used instead)"
    fi
    
    # Check GitHub authentication globally (works for all repos)
    print_thinking "Checking global GitHub authentication setup..."
    
    # Check GitHub CLI first (preferred method)
    if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
        print_verbose "✓ GitHub CLI authenticated globally"
        auth_method="github-cli"
    elif ssh -T git@github.com 2>&1 | grep -q "successfully authenticated"; then
        print_verbose "✓ SSH key authenticated globally with GitHub"
        auth_method="ssh"
    else
        print_error "✗ No global GitHub authentication found"
        print_verbose "  You need to authenticate with GitHub once to use superclaude"
        print_verbose "  Choose one of these options:"
        print_verbose "  1. GitHub CLI (recommended): 'brew install gh && gh auth login'"
        print_verbose "  2. SSH key: Generate with 'ssh-keygen -t ed25519 -C \"your@email.com\"'"
        print_verbose "     Then add to GitHub: https://github.com/settings/keys"
        print_verbose "  3. Test SSH with: 'ssh -T git@github.com'"
        missing_deps+=("github-authentication")
        all_good=false
    fi
    
    # Also check GitHub CLI for enhanced features (optional but recommended)
    print_thinking "Checking GitHub CLI for enhanced features..."
    if command -v gh >/dev/null 2>&1; then
        local gh_version=$(gh --version | head -1 | cut -d' ' -f3)
        print_verbose "✓ GitHub CLI found (version: $gh_version)"
    else
        print_verbose "⚠ GitHub CLI not found (optional, but enables enhanced workflows)"
    fi
    
    if [ "$all_good" = false ]; then
        print_error "Missing required dependencies: ${missing_deps[*]}"
        echo ""
        printf "${YELLOW}📋 Installation Guide:${NC}\n"
        
        for dep in "${missing_deps[@]}"; do
            case $dep in
                "claude")
                    printf "${BLUE}├─ Claude Code:${NC} npm install -g @anthropic-ai/claude-code\n"
                    printf "${BLUE}│  ${NC} Then run: claude (and complete authentication)\n"
                    ;;
                "claude-authentication")
                    printf "${BLUE}├─ Claude Code Authentication:${NC} Run 'claude' and complete setup\n"
                    printf "${BLUE}│  ${NC} Choose from Anthropic Console, Claude Pro/Max, or Enterprise options\n"
                    ;;
                "git")
                    printf "${BLUE}├─ Git:${NC} https://git-scm.com/downloads\n"
                    printf "${BLUE}│  ${NC} Or: brew install git (macOS) / apt install git (Linux)\n"
                    ;;
                "git-config")
                    printf "${BLUE}├─ Git Configuration:${NC} git config --global user.name \"Your Name\"\n"
                    printf "${BLUE}│  ${NC} And run: git config --global user.email \"your@email.com\"\n"
                    ;;
                "node")
                    printf "${BLUE}├─ Node.js:${NC} https://nodejs.org/en/download/\n"
                    printf "${BLUE}│  ${NC} Or: brew install node (macOS) / apt install nodejs (Linux)\n"
                    ;;
                "github-authentication")
                    printf "${BLUE}├─ GitHub Authentication:${NC} Set up global GitHub access\n"
                    printf "${BLUE}│  ${NC} Option 1 (recommended): Install GitHub CLI: brew install gh && gh auth login\n"
                    printf "${BLUE}│  ${NC} Option 2: SSH key: ssh-keygen -t ed25519 -C \"your@email.com\"\n"
                    printf "${BLUE}│  ${NC}   Then add to GitHub: https://github.com/settings/keys\n"
                    printf "${BLUE}│  ${NC}   Test with: ssh -T git@github.com\n"
                    ;;
            esac
        done
        
        printf "${BLUE}└─${NC} After installation, run this command again\n"
        echo ""
        exit 1
    fi
    
    print_success "All dependencies verified successfully"
    print_verbose "System ready for AI-powered development operations"
    
    # Save successful verification to cache
    save_cache "$auth_method"
    
    # Check for updates (non-blocking)
    check_for_updates
}

# Get codebase context for analysis
get_codebase_context() {
    local file_list=$(find . -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" -o -name "*.json" | grep -v node_modules | grep -v .git | head -20)
    local package_json=""
    if [ -f "package.json" ]; then
        package_json=$(head -30 package.json)
    fi
    
    echo "Files in codebase: $file_list

Package.json:
$package_json"
}

# Ensure push authentication is properly configured
ensure_push_auth() {
    local remote_url=$(git remote get-url origin 2>/dev/null || echo "")
    
    if [[ "$remote_url" == https://github.com/* ]]; then
        # HTTPS remote - ensure GitHub CLI credential helper is configured
        if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
            print_verbose "Configuring GitHub CLI credential helper for HTTPS remote"
            git config --local credential.https://github.com.helper ""
            git config --local credential.https://github.com.helper "!gh auth git-credential"
        else
            print_error "HTTPS remote detected but no GitHub CLI authentication found"
            print_verbose "  Either:"
            print_verbose "  1. Run 'gh auth login' to authenticate with GitHub CLI"
            print_verbose "  2. Switch to SSH: git remote set-url origin git@github.com:$(echo "$remote_url" | sed 's|https://github.com/||' | sed 's|\.git$||').git"
            exit 1
        fi
    elif [[ "$remote_url" == git@github.com:* ]]; then
        # SSH remote - verify SSH key works
        if ! ssh -T git@github.com 2>&1 | grep -q "successfully authenticated"; then
            print_error "SSH remote detected but SSH authentication failed"
            print_verbose "  Either:"
            print_verbose "  1. Check your SSH key: ssh -T git@github.com"
            print_verbose "  2. Generate a new key: ssh-keygen -t ed25519 -C \"your@email.com\""
            print_verbose "  3. Add it to GitHub: https://github.com/settings/keys"
            exit 1
        fi
    fi
}

# COMMIT command (restored working functionality)
cmd_commit() {
    print_header "AI Commit"
    print_step "🔧 Initializing AI-powered commit workflow..."
    print_substep "Verifying Claude AI and system dependencies..."
    check_dependencies
    check_git_repo
    ensure_push_auth
    
    print_step "🔍 Repository status check..."
    print_substep "Checking working directory for changes..."
    local status_output=$(git status --porcelain)
    
    if [ -z "$status_output" ]; then
        print_success "Nothing to commit, working tree clean"
        exit 0
    fi
    
    local file_count=$(echo "$status_output" | wc -l | tr -d ' ')
    print_verbose "Found $file_count modified files"
    
    print_step "📊 Analyzing changes in detail..."
    print_substep "Scanning modified files..."
    
    # Stage all changes first
    print_step "📦 Staging all changes..."
    print_substep "Running git add . to stage all modifications..."
    git add .
    print_verbose "All changes staged successfully"
    
    # Get detailed change information
    print_substep "Gathering change statistics..."
    local file_changes=$(git diff --cached --name-only)
    local diff_stat=$(git diff --cached --stat)
    local lines_changed=$(git diff --cached --numstat | awk '{added+=$1; removed+=$2} END {print "+"added"/-"removed}')
    
    print_verbose "Files changed: $(echo "$file_changes" | wc -l | tr -d ' ')"
    print_verbose "Lines changed: $lines_changed"
    
    print_step "🤖 Preparing Claude AI analysis..."
    print_substep "Building context for AI commit message generation..."
    print_thinking "Analyzing code changes to understand the intent and impact..."
    
    # Add guidance context if provided
    local additional_context=""
    if [ -n "$COMMIT_GUIDANCE" ]; then
        additional_context="Additional context: $COMMIT_GUIDANCE"
        print_verbose "Using additional context: $COMMIT_GUIDANCE"
    fi
    
    # Load and process commit prompt template
    local prompt_template=$(load_prompt "commit")
    local commit_prompt_1=$(process_template "$prompt_template" "file_changes" "$file_changes")
    local commit_prompt_2=$(process_template "$commit_prompt_1" "diff_stat" "$diff_stat")
    local commit_prompt=$(process_template "$commit_prompt_2" "additional_context" "$additional_context")

    print_substep "Sending analysis request to Claude..."
    print_thinking "Determining commit type (feat/fix/refactor/etc.) based on file patterns..."
    print_thinking "Crafting concise summary that captures the essence of changes..."
    
    # Use Claude to generate commit message
    local commit_msg_raw=$(claude --print "$commit_prompt")
    
    print_substep "Processing Claude's response..."
    print_thinking "Cleaning up formatting and ensuring conventional commit compliance..."
    
    # Clean up the commit message - remove markdown formatting and AI prefixes
    local commit_msg=$(echo "$commit_msg_raw" | \
        sed 's/^```.*$//' | \
        sed 's/^```$//' | \
        sed '/^$/d' | \
        sed 's/^[Bb]ased on the changes, here'\''s the commit message:[ ]*//' | \
        sed 's/^[Hh]ere'\''s the commit message:[ ]*//' | \
        sed 's/^[Cc]ommit message:[ ]*//' | \
        sed 's/^[Tt]he commit message is:[ ]*//' | \
        sed 's/^[Hh]ere is the commit message:[ ]*//' | \
        sed 's/^[Hh]ere'\''s a commit message:[ ]*//' | \
        sed 's/^[Ff]or this commit:[ ]*//' | \
        sed 's/^[Tt]his commit:[ ]*//' | \
        sed 's/^[Aa]s requested:[ ]*//' | \
        sed 's/^[Ss]ure:[ ]*//' | \
        head -20 | \
        sed '/^$/d')
    
    printf "${YELLOW}📝 Generated commit message:${NC}\n"
    echo "$commit_msg"
    echo ""
    
    # Interactive confirmation if enabled
    if [ "$INTERACTIVE_MODE" = true ]; then
        print_step "🤔 Interactive confirmation..."
        print_substep "Review the generated commit message above"
        
        # Check if we're in a proper interactive terminal
        if [ ! -t 0 ]; then
            print_error "Interactive mode requires a terminal (not piped input)"
            print_verbose "Falling back to non-interactive mode"
            print_step "🤖 Auto-proceeding with AI-generated commit message"
        else
            local attempt_count=0
            local max_attempts=5
            
            while true; do
                printf "${YELLOW}❓ Proceed with this commit message? (y/n/e/h): ${NC}"
                
                # Use read with timeout to prevent infinite loops
                if read -r response; then
                    # Check for empty response (happens with EOF or closed pipes)
                    if [ -z "$response" ]; then
                        attempt_count=$((attempt_count + 1))
                        if [ $attempt_count -ge $max_attempts ]; then
                            print_error "Too many empty responses, assuming non-interactive environment"
                            print_verbose "Auto-proceeding with commit"
                            break
                        fi
                        print_verbose "Empty response received (attempt $attempt_count/$max_attempts)"
                        continue
                    fi
                    
                    case $response in
                        [Yy]*)
                            print_verbose "User confirmed commit message"
                            break
                            ;;
                        [Nn]*)
                            print_verbose "User cancelled commit"
                            print_step "❌ Commit cancelled by user"
                            exit 0
                            ;;
                        [Ee]*)
                            print_substep "Opening editor for commit message..."
                            print_thinking "Allowing user to edit the AI-generated message..."
                            
                            # Create temporary file with commit message
                            local temp_file=$(mktemp)
                            echo "$commit_msg" > "$temp_file"
                            
                            # Open editor (prefer EDITOR env var, fallback to common editors)
                            if [ -n "$EDITOR" ]; then
                                $EDITOR "$temp_file"
                            elif command -v code >/dev/null 2>&1; then
                                code --wait "$temp_file"
                            elif command -v nano >/dev/null 2>&1; then
                                nano "$temp_file"
                            elif command -v vim >/dev/null 2>&1; then
                                vim "$temp_file"
                            else
                                print_error "No editor found. Set EDITOR environment variable or install nano/vim"
                                rm "$temp_file"
                                exit 1
                            fi
                            
                            # Read edited message
                            commit_msg=$(cat "$temp_file")
                            rm "$temp_file"
                            
                            print_verbose "User edited commit message"
                            printf "${YELLOW}📝 Updated commit message:${NC}\n"
                            echo "$commit_msg"
                            echo ""
                            # Reset attempt counter after successful edit
                            attempt_count=0
                            ;;
                        [Hh]*)
                            printf "${BLUE}💡 Help:${NC}\n"
                            printf "  ${GREEN}y/yes${NC}  - Proceed with the commit using this message\n"
                            printf "  ${GREEN}n/no${NC}   - Cancel the commit entirely\n"
                            printf "  ${GREEN}e/edit${NC} - Open editor to modify the commit message\n"
                            printf "  ${GREEN}h/help${NC} - Show this help message\n"
                            echo ""
                            # Reset attempt counter after showing help
                            attempt_count=0
                            ;;
                        *)
                            print_verbose "Invalid response: '$response'"
                            printf "${RED}❌ Invalid option. Use y/n/e/h${NC}\n"
                            attempt_count=$((attempt_count + 1))
                            if [ $attempt_count -ge $max_attempts ]; then
                                print_error "Too many invalid responses, assuming non-interactive environment"
                                print_verbose "Auto-proceeding with commit"
                                break
                            fi
                            ;;
                    esac
                else
                    # read command failed (EOF, etc.)
                    print_error "Failed to read user input, assuming non-interactive environment"
                    print_verbose "Auto-proceeding with commit"
                    break
                fi
            done
        fi
    else
        print_verbose "Auto-proceeding with commit (non-interactive mode)"
    fi
    
    print_step "💾 Creating commit..."
    print_substep "Executing git commit with AI-generated message..."
    git commit -m "$commit_msg"
    local commit_hash=$(git rev-parse --short HEAD)
    local full_commit_hash=$(git rev-parse HEAD)
    print_verbose "Commit created successfully: $commit_hash"
    
    # Auto-annotate the new commit with the same message
    print_step "📝 Adding AI annotation to commit..."
    print_substep "Using the same AI-generated message as annotation..."
    print_thinking "Since we already have a descriptive Claude-generated message, using it as annotation..."
    
    # Use the same commit message as annotation (no need for extra Claude call)
    print_verbose "Reusing AI-generated commit message for annotation"
    
    # Add the note to the commit using the same message
    print_substep "Adding commit message as annotation note..."
    if git notes add -m "$commit_msg" "$full_commit_hash" 2>/dev/null; then
        print_verbose "✓ AI annotation added to commit: $commit_hash"
    else
        print_verbose "⚠ Note addition failed (may already exist)"
    fi
    
    # Push to current branch
    local current_branch=$(git branch --show-current)
    print_step "🚢 Pushing to remote repository..."
    print_substep "Pushing to origin/$current_branch..."
    print_thinking "Synchronizing local changes with remote repository..."
    
    # Push with proper authentication (already configured by ensure_push_auth)
    git push origin "$current_branch"
    print_verbose "Push completed successfully"
    
    print_success "Commit complete! 🎉"
    print_verbose "AI-powered commit workflow finished"
}

# README command
cmd_readme() {
    print_header "AI README Generator"
    print_verbose "Initializing intelligent README generation system..."
    check_dependencies
    check_git_repo
    
    print_step "🔍 Codebase analysis..."
    print_substep "Scanning project structure and dependencies..."
    print_thinking "Identifying key technologies and frameworks..."
    local context=$(get_codebase_context)
    local file_count=$(echo "$context" | grep -c "\.ts\|\.tsx\|\.js\|\.jsx")
    print_verbose "Analyzed ${file_count} source files for context"
    
    print_step "🤖 README generation with Claude AI..."
    print_substep "Preparing comprehensive project analysis..."
    print_thinking "Analyzing project architecture to create engaging documentation..."
    print_thinking "Crafting professional README with installation and usage guides..."
    
    local readme_content=$(claude --print "Analyze this codebase and create a comprehensive README.md:

$context

Create a professional README with:
1. Project title and description
2. Features overview
3. Installation instructions
4. Usage examples
5. Tech stack
6. Project structure
7. Contributing guidelines

Make it engaging and informative. Return ONLY the README content, no extra text or markdown code blocks.")
    
    print_substep "Processing Claude's README response..."
    print_thinking "Cleaning up formatting and ensuring professional presentation..."
    
    # Clean up any markdown formatting
    local cleaned_readme=$(echo "$readme_content" | sed 's/^```.*$//' | sed 's/^```$//')
    local readme_length=$(echo "$cleaned_readme" | wc -l | tr -d ' ')
    
    print_verbose "Claude generated ${readme_length} lines of README content"
    
    printf "${YELLOW}📝 Generated README:${NC}\n"
    echo "$cleaned_readme"
    echo ""
    
    print_step "💾 README file creation..."
    # Ask user if they want to save it
    printf "💾 Save to README.md? (y/N): "
    read -r response
    if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
        print_substep "Writing README.md file..."
        echo "$cleaned_readme" > README.md
        local readme_size=$(wc -c < README.md)
        print_verbose "README.md saved (${readme_size} bytes)"
        print_success "README.md created!"
    else
        print_verbose "User chose not to save README"
        print_step "README not saved."
    fi
}

# REVIEW command
cmd_review() {
    print_header "AI Code Review"
    print_verbose "Initializing comprehensive code review system..."
    check_dependencies
    check_git_repo
    
    print_step "🔍 Codebase security and quality analysis..."
    print_substep "Scanning for potential vulnerabilities and code smells..."
    print_thinking "Analyzing architecture patterns and best practices adherence..."
    local context=$(get_codebase_context)
    local file_count=$(echo "$context" | grep -c "\.ts\|\.tsx\|\.js\|\.jsx")
    print_verbose "Analyzing ${file_count} source files for review"
    
    print_step "🤖 Deep code analysis with Claude AI..."
    print_substep "Preparing comprehensive code review analysis..."
    print_thinking "Evaluating code quality, security, and maintainability..."
    print_thinking "Identifying refactoring opportunities and technical debt..."
    
    local review_content=$(claude --print "Perform a comprehensive code review of this codebase:

$context

Analyze for:
1. Code quality and maintainability
2. Security vulnerabilities
3. Performance issues
4. Best practices adherence
5. Architecture improvements
6. Technical debt
7. Refactoring opportunities

Provide specific, actionable feedback with examples. Be thorough but constructive.")
    
    print_substep "Processing comprehensive code review..."
    local review_length=$(echo "$review_content" | wc -l | tr -d ' ')
    print_verbose "Claude generated ${review_length} lines of code review analysis"
    
    printf "${YELLOW}📋 Code Review Results:${NC}\n"
    echo "$review_content"
    echo ""
    
    print_step "💾 Code review documentation..."
    # Ask user if they want to save it
    printf "💾 Save review to docs/code-review.md? (y/N): "
    read -r response
    if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
        print_substep "Creating docs directory and saving review..."
        mkdir -p docs
        echo "$review_content" > docs/code-review.md
        local review_size=$(wc -c < docs/code-review.md)
        print_verbose "Code review saved (${review_size} bytes)"
        print_success "Code review saved to docs/code-review.md!"
    else
        print_verbose "User chose not to save code review"
    fi
}

# ANNOTATE command
cmd_annotate() {
    print_header "AI Commit Annotator"
    print_verbose "Initializing AI-powered commit annotation system..."
    check_dependencies
    check_git_repo
    
    print_step "🔍 Repository analysis..."
    print_substep "Scanning git repository structure..."
    local total_commits=$(git rev-list --count HEAD)
    local current_branch=$(git branch --show-current)
    
    print_verbose "Repository statistics:"
    print_verbose "  ├─ Current branch: ${current_branch}"
    print_verbose "  └─ Total commits: ${total_commits}"
    
    if [ "$total_commits" -eq 0 ]; then
        print_error "No commits found in repository!"
        exit 1
    fi
    
    print_step "📝 Commit annotation process..."
    print_substep "Extracting commit history for analysis..."
    print_thinking "Getting all commit hashes in chronological order..."
    
    print_verbose "Starting annotation of ${total_commits} commits..."
    
    # Process each commit
    local processed_count=0
    local annotated_count=0
    local skipped_count=0
    local failed_count=0
    
    # Write commit hashes to temporary file to avoid subshell issues
    local temp_commits_file=$(mktemp)
    git rev-list HEAD > "$temp_commits_file"
    
    # Process each commit
    while IFS= read -r commit_hash; do
        if [ -z "$commit_hash" ]; then
            continue
        fi
        
        processed_count=$((processed_count + 1))
        
        # Show progress
        print_progress "Processing commit ${processed_count}/${total_commits}: ${commit_hash:0:8}"
        
        # Check if commit already has a note
        print_thinking "Checking for existing note..."
        if git notes show "$commit_hash" >/dev/null 2>&1; then
            print_verbose "  └─ Skipping (already has note): ${commit_hash:0:8}"
            skipped_count=$((skipped_count + 1))
            continue
        fi
        
        print_thinking "Analyzing commit diff for AI annotation..."
        print_substep "Extracting commit information..."
        
        # Get commit info
        local commit_subject=$(git log --format="%s" -n 1 "$commit_hash" 2>/dev/null)
        local commit_author=$(git log --format="%an" -n 1 "$commit_hash" 2>/dev/null)
        local commit_date=$(git log --format="%ad" --date=short -n 1 "$commit_hash" 2>/dev/null)
        
        if [ -z "$commit_subject" ]; then
            print_verbose "  └─ Skipping (invalid commit): ${commit_hash:0:8}"
            failed_count=$((failed_count + 1))
            continue
        fi
        
        print_verbose "  ├─ Subject: ${commit_subject}"
        print_verbose "  ├─ Author: ${commit_author}"
        print_verbose "  └─ Date: ${commit_date}"
        
        # Get the diff for this commit
        print_substep "Extracting diff for analysis..."
        local commit_diff=$(git show --format="" "$commit_hash" 2>/dev/null | head -100)  # Limit diff size
        local diff_size=$(echo "$commit_diff" | wc -l | tr -d ' ')
        
        if [ -z "$commit_diff" ]; then
            print_verbose "  └─ Skipping (no diff found): ${commit_hash:0:8}"
            skipped_count=$((skipped_count + 1))
            continue
        fi
        
        print_verbose "  └─ Diff extracted (${diff_size} lines)"
        
        # Send to Claude for annotation
        print_substep "Generating AI annotation..."
        print_thinking "Sending diff to Claude for intelligent analysis..."
        
        local annotation_prompt="Analyze this git commit and create a concise but informative note:

Original commit message: $commit_subject
Author: $commit_author  
Date: $commit_date

Diff:
$commit_diff

Create a brief note that explains what this commit actually accomplished in clear, technical language. Focus on:
- What was changed (files, functions, features)
- Why it was changed (purpose, problem solved)
- Any important technical details

Keep it concise but informative. Use conventional commit format if appropriate.
Return ONLY the note content, no markdown formatting."

        # Try Claude annotation with error handling
        local annotation=""
        if annotation=$(claude --print "$annotation_prompt" 2>/dev/null); then
            # Check if Claude returned valid content
            if [ -n "$annotation" ] && [[ "$annotation" != *"error"* ]] && [[ "$annotation" != *"Error"* ]]; then
                print_verbose "Claude annotation successful"
            else
                print_verbose "Claude returned error, using fallback"
                annotation="AI annotation failed - Commit: $commit_subject (${commit_date})"
            fi
        else
            print_verbose "Claude API call failed, using fallback"
            annotation="AI annotation failed - Commit: $commit_subject (${commit_date})"
        fi
        
        # Clean up annotation
        local cleaned_annotation=$(echo "$annotation" | sed 's/^```.*$//' | sed 's/^```$//' | head -10)
        local annotation_length=$(echo "$cleaned_annotation" | wc -c)
        
        print_verbose "Generated annotation (${annotation_length} chars)"
        
        # Add the note
        print_substep "Adding git note..."
        if git notes add -m "$cleaned_annotation" "$commit_hash" 2>/dev/null; then
            print_verbose "✓ Note added successfully: ${commit_hash:0:8}"
            annotated_count=$((annotated_count + 1))
        else
            print_error "Failed to add note to commit ${commit_hash:0:8}"
            failed_count=$((failed_count + 1))
        fi
        
        # Small delay to avoid overwhelming Claude API
        if [ "$VERBOSE_MODE" = true ]; then
            sleep 0.2
        else
            sleep 0.1
        fi
        
        # Progress update every 25 commits in non-verbose mode
        if [ "$VERBOSE_MODE" != true ] && [ $((processed_count % 25)) -eq 0 ]; then
            echo "⏳ Progress: ${processed_count}/${total_commits} commits processed (${annotated_count} annotated)"
        fi
        
    done < "$temp_commits_file"
    
    # Cleanup temp file
    rm -f "$temp_commits_file"
    
    print_step "📊 Annotation summary..."
    print_success "Annotation process complete!"
    print_verbose "Final statistics:"
    printf "  ├─ Total commits processed: ${processed_count}\n"
    printf "  ├─ New annotations added: ${annotated_count}\n"
    printf "  ├─ Skipped (already had notes): ${skipped_count}\n"
    printf "  ├─ Failed/Invalid commits: ${failed_count}\n"
    if [ "$processed_count" -gt 0 ]; then
        printf "  └─ Success rate: $(( (annotated_count * 100) / processed_count ))%%\n"
    fi
    
    print_step "💡 Usage tip..."
    printf "${YELLOW}💡 View annotated history with:${NC}\n"
    printf "  ${GREEN}git log --show-notes${NC}     # Show commits with notes\n"
    printf "  ${GREEN}git log --show-notes --oneline${NC}  # Compact view\n\n"
    
    print_verbose "AI-powered commit annotation workflow completed"
}

# BRAINSTORM command
cmd_brainstorm() {
    print_header "AI Brainstorm Session"
    print_verbose "Initializing AI brainstorming session..."
    check_dependencies
    check_git_repo
    
    print_step "🧠 Analyzing project for brainstorm ideas..."
    local context=$(get_codebase_context)
    
    print_step "🤖 Brainstorming with Claude..."
    
    local brainstorm_content=$(claude --print "Analyze this codebase and brainstorm improvement ideas:

$context

Brainstorm:
1. New feature ideas that would add value
2. Performance optimization opportunities
3. Developer experience improvements
4. Architecture evolution suggestions
5. Integration possibilities
6. User experience enhancements
7. Technical debt reduction strategies

Be creative but practical. Focus on actionable ideas with clear benefits.")
    
    printf "${YELLOW}💡 Brainstorm Results:${NC}\n"
    echo "$brainstorm_content"
    echo ""
    
    # Ask user if they want to save it
    printf "💾 Save brainstorm to docs/ideas.md? (y/N): "
    read -r response
    if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
        mkdir -p docs
        echo "$brainstorm_content" > docs/ideas.md
        print_success "Brainstorm saved to docs/ideas.md!"
    fi
}

# DOCS command
cmd_docs() {
    print_header "AI Documentation Generator"
    print_verbose "Initializing AI documentation generation..."
    check_dependencies
    check_git_repo
    
    print_step "📚 Analyzing codebase for documentation..."
    local context=$(get_codebase_context)
    
    print_step "🤖 Generating documentation with Claude..."
    
    local docs_content=$(claude --print "Create comprehensive technical documentation for this codebase:

$context

Generate documentation covering:
1. Architecture overview
2. Key components and their roles
3. Data flow and interactions
4. Configuration options
5. Development setup
6. Testing strategy
7. Deployment process
8. Troubleshooting guide

Make it detailed and developer-friendly.")
    
    printf "${YELLOW}📖 Generated Documentation:${NC}\n"
    echo "$docs_content"
    echo ""
    
    # Ask user if they want to save it
    printf "💾 Save to docs/technical-docs.md? (y/N): "
    read -r response
    if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
        mkdir -p docs
        echo "$docs_content" > docs/technical-docs.md
        print_success "Documentation saved to docs/technical-docs.md!"
    fi
}

# CHANGELOG command
cmd_changelog() {
    print_header "AI Changelog Generator"
    print_verbose "Initializing intelligent changelog generation system..."
    check_dependencies
    check_git_repo
    
    # Count total commits for progress tracking
    print_step "🔍 Repository analysis..."
    print_substep "Scanning git repository structure..."
    local total_commits=$(git rev-list --count HEAD)
    local total_branches=$(git branch -r | wc -l | tr -d ' ')
    local repo_age=$(git log --reverse --pretty=format:'%cr' | head -1)
    
    print_verbose "Repository statistics:"
    print_verbose "  ├─ Total commits: ${total_commits}"
    print_verbose "  ├─ Remote branches: ${total_branches}"
    print_verbose "  └─ Repository age: ${repo_age}"
    
    print_step "📅 Extracting commit history..."
    print_substep "Querying git log with structured format..."
    print_thinking "Organizing commits chronologically for analysis..."
    
    # Get all commit history with dates
    local commit_history=$(git log --pretty=format:"%h|%ad|%s|%an" --date=short --reverse)
    
    if [ -z "$commit_history" ]; then
        print_error "No commit history found!"
        exit 1
    fi
    
    print_step "📝 Extracting commit notes for enhanced context..."
    print_substep "Checking for AI-generated annotations..."
    print_thinking "Gathering git notes to provide richer commit context..."
    
    # Enhanced commit history with notes
    local enhanced_history=""
    local commits_with_notes=0
    
    echo "$commit_history" | while read -r line; do
        if [ -z "$line" ]; then continue; fi
        
        local commit_hash=$(echo "$line" | cut -d'|' -f1)
        local commit_date=$(echo "$line" | cut -d'|' -f2)
        local commit_msg=$(echo "$line" | cut -d'|' -f3)
        local commit_author=$(echo "$line" | cut -d'|' -f4)
        
        # Check if this commit has a note
        local commit_note=""
        if git notes show "$commit_hash" >/dev/null 2>&1; then
            commit_note=$(git notes show "$commit_hash" 2>/dev/null)
            commits_with_notes=$((commits_with_notes + 1))
            enhanced_history="${enhanced_history}\n${commit_hash}|${commit_date}|${commit_msg}|${commit_author}|NOTE: ${commit_note}"
        else
            enhanced_history="${enhanced_history}\n${commit_hash}|${commit_date}|${commit_msg}|${commit_author}|"
        fi
    done
    
    print_verbose "Found ${commits_with_notes} commits with AI annotations"
    
    # Use enhanced history if we have notes, otherwise use regular history
    local history_for_analysis="$commit_history"
    if [ "$commits_with_notes" -gt 0 ]; then
        history_for_analysis="$enhanced_history"
        print_verbose "Using enhanced commit history with AI annotations"
    else
        print_verbose "No AI annotations found, using standard commit history"
    fi
    
    print_verbose "Successfully extracted ${total_commits} commits"
    
    # Get date range for context
    print_substep "Calculating project timeline..."
    local first_date=$(git log --pretty=format:'%ad' --date=short | tail -1)
    local last_date=$(git log --pretty=format:'%ad' --date=short | head -1)
    local unique_days=$(git log --pretty=format:'%ad' --date=short | sort -u | wc -l | tr -d ' ')
    
    print_verbose "Timeline analysis:"
    print_verbose "  ├─ Start date: ${first_date}"
    print_verbose "  ├─ End date: ${last_date}"
    print_verbose "  └─ Active days: ${unique_days}"
    
    print_step "🤖 Main changelog generation..."
    print_substep "Preparing focused analysis for Claude AI..."
    print_thinking "Using recent commits to avoid token limits..."
    
    # Limit commit history to recent commits to avoid token issues
    local recent_commit_history=$(echo "$history_for_analysis" | tail -100)
    local recent_commit_count=$(echo "$recent_commit_history" | wc -l | tr -d ' ')
    print_verbose "Using ${recent_commit_count} recent commits for main changelog"
    
    # Load and process changelog prompt template
    local changelog_template=$(load_prompt "changelog")
    local changelog_prompt=$(process_template "$changelog_template" "commits" "$recent_commit_history")
    
    local changelog_content=$(claude --print "$changelog_prompt" 2>&1)
    
    # Check for errors
    if [[ "$changelog_content" == *"error"* ]] || [[ "$changelog_content" == *"Error"* ]] || [ -z "$changelog_content" ]; then
        print_error "Claude AI failed for main changelog, using existing or creating simple one..."
        if [ -f "CHANGELOG.md" ]; then
            print_verbose "Keeping existing CHANGELOG.md"
            local changelog_content=$(cat CHANGELOG.md)
        else
            print_verbose "Creating simple changelog format..."
            local changelog_content="# Changelog

## Recent Changes

$(git log --pretty=format:'- %ad: %s' --date=short -n 50)

---
*This changelog is automatically generated.*"
        fi
    fi
    
    print_substep "Processing Claude's response..."
    print_thinking "Cleaning up markdown artifacts and formatting..."
    
    # Clean up any markdown formatting artifacts
    local cleaned_changelog=$(echo "$changelog_content" | sed 's/^```.*$//' | sed 's/^```$//')
    local changelog_length=$(echo "$cleaned_changelog" | wc -l | tr -d ' ')
    
    print_verbose "Claude generated ${changelog_length} lines of changelog content"
    
    printf "${YELLOW}📝 Generated Main Changelog:${NC}\n"
    echo "$cleaned_changelog"
    echo ""
    
    # Create changelogs directory structure
    print_step "📁 Directory structure setup..."
    print_substep "Creating changelogs directory..."
    mkdir -p changelogs
    print_verbose "Directory structure created successfully"
    
    # Save main changelog
    print_substep "Writing main CHANGELOG.md..."
    echo "$cleaned_changelog" > CHANGELOG.md
    local changelog_size=$(wc -c < CHANGELOG.md)
    print_verbose "Main changelog saved (${changelog_size} bytes)"
    print_success "Main CHANGELOG.md created!"
    
    # Generate smart consolidated changelogs
    print_step "📅 Intelligent daily summary generation..."
    print_substep "Extracting recent commit patterns (last 100 commits)..."
    print_thinking "Limiting data size to avoid Claude API issues..."
    
    # Get recent daily commits for AI analysis (limit to avoid token issues)
    local daily_commits=$(git log --pretty=format:"%ad|%s" --date=short -n 100 | sort | uniq)
    local daily_commit_count=$(echo "$daily_commits" | wc -l | tr -d ' ')
    
    print_verbose "Extracted ${daily_commit_count} recent entries for analysis"
    print_substep "Sending daily patterns to Claude AI..."
    print_thinking "Creating focused analysis of recent development activity..."
    
    # Test if Claude CLI is working properly
    print_thinking "Testing Claude CLI connection..."
    local test_response=$(claude --print "Say 'Claude is working'" 2>&1)
    if [[ "$test_response" == *"Claude is working"* ]]; then
        print_verbose "✓ Claude CLI connection verified"
    else
        print_error "✗ Claude CLI test failed: $test_response"
        print_verbose "Falling back to simple git log format..."
        # Fallback to simple format
        local daily_file="changelogs/daily-changelog.md"
        echo "# Daily Development Summary" > "$daily_file"
        echo "" >> "$daily_file"
        echo "A summary of recent development progress from $first_date to $last_date." >> "$daily_file"
        echo "" >> "$daily_file"
        echo "## Recent Activity" >> "$daily_file"
        echo "" >> "$daily_file"
        git log --pretty=format:"- %ad: %s" --date=short -n 50 >> "$daily_file"
        print_verbose "Fallback daily summary created"
        return 0
    fi
    
    # Load and process daily changelog prompt template
    local daily_template=$(load_prompt "daily-changelog")
    local daily_prompt=$(process_template "$daily_template" "commits" "$daily_commits")
    
    local daily_content=$(claude --print "$daily_prompt" 2>&1)
    
    # Check if Claude returned an error
    if [[ "$daily_content" == *"error"* ]] || [[ "$daily_content" == *"Error"* ]] || [ -z "$daily_content" ]; then
        print_error "Claude AI failed for daily changelog: $daily_content"
        print_verbose "Creating fallback daily changelog..."
        local daily_file="changelogs/daily-changelog.md"
        echo "# Daily Development Summary" > "$daily_file"
        echo "" >> "$daily_file"
        echo "A summary of recent development progress from $first_date to $last_date." >> "$daily_file"
        echo "" >> "$daily_file"
        echo "## Recent Activity" >> "$daily_file"
        echo "" >> "$daily_file"
        git log --pretty=format:"- %ad: %s" --date=short -n 50 >> "$daily_file"
        print_verbose "Fallback daily summary created"
    else
        print_substep "Processing daily summary response..."
        local daily_content_length=$(echo "$daily_content" | wc -l | tr -d ' ')
        print_verbose "Claude generated ${daily_content_length} lines of daily summary"
        
        print_substep "Writing daily development summary..."
        local daily_file="changelogs/daily-changelog.md"
        echo "# Daily Development Summary" > "$daily_file"
        echo "" >> "$daily_file"
        echo "A human-readable summary of daily development progress from $first_date to $last_date." >> "$daily_file"
        echo "" >> "$daily_file"
        echo "$daily_content" >> "$daily_file"
        
        local daily_file_size=$(wc -c < "$daily_file")
        print_verbose "Daily summary saved (${daily_file_size} bytes)"
    fi
    
    # Generate weekly changelog
    print_step "📅 Intelligent weekly summary generation..."
    print_substep "Extracting recent weekly patterns (last 50 commits)..."
    print_thinking "Creating weekly overview with limited data set..."
    
    local weekly_commits=$(git log --pretty=format:"%ad|%s" --date=format:'%Y-W%U' -n 50)
    local weekly_commit_count=$(echo "$weekly_commits" | wc -l | tr -d ' ')
    
    print_verbose "Extracted ${weekly_commit_count} weekly entries for analysis"
    print_substep "Sending weekly patterns to Claude AI..."
    
    # Load and process weekly changelog prompt template
    local weekly_template=$(load_prompt "weekly-changelog")
    local weekly_prompt=$(process_template "$weekly_template" "commits" "$weekly_commits")
    
    local weekly_content=$(claude --print "$weekly_prompt" 2>&1)
    
    # Check for errors
    if [[ "$weekly_content" == *"error"* ]] || [[ "$weekly_content" == *"Error"* ]] || [ -z "$weekly_content" ]; then
        print_error "Claude AI failed for weekly changelog, creating fallback..."
        local weekly_file="changelogs/weekly-changelog.md"
        echo "# Weekly Development Summary" > "$weekly_file"
        echo "" >> "$weekly_file"
        echo "A summary of recent weekly development from $first_date to $last_date." >> "$weekly_file"
        echo "" >> "$weekly_file"
        echo "## Recent Weekly Activity" >> "$weekly_file"
        echo "" >> "$weekly_file"
        git log --pretty=format:"- %ad: %s" --date=format:'Week %Y-%U' -n 30 >> "$weekly_file"
        print_verbose "Fallback weekly summary created"
    else
        print_substep "Processing weekly summary response..."
        local weekly_content_length=$(echo "$weekly_content" | wc -l | tr -d ' ')
        print_verbose "Claude generated ${weekly_content_length} lines of weekly summary"
        
        print_substep "Writing weekly development summary..."
        local weekly_file="changelogs/weekly-changelog.md"
        echo "# Weekly Development Summary" > "$weekly_file"
        echo "" >> "$weekly_file"
        echo "A strategic overview of weekly development milestones from $first_date to $last_date." >> "$weekly_file"
        echo "" >> "$weekly_file"
        echo "$weekly_content" >> "$weekly_file"
        
        local weekly_file_size=$(wc -c < "$weekly_file")
        print_verbose "Weekly summary saved (${weekly_file_size} bytes)"
    fi
    
    # Generate monthly changelog  
    print_step "📅 Strategic monthly overview generation..."
    print_substep "Extracting recent monthly patterns (last 75 commits)..."
    print_thinking "Creating monthly strategic overview with manageable data set..."
    
    local monthly_commits=$(git log --pretty=format:"%ad|%s" --date=format:'%Y-%m' -n 75)
    local monthly_commit_count=$(echo "$monthly_commits" | wc -l | tr -d ' ')
    
    print_verbose "Extracted ${monthly_commit_count} monthly entries for analysis"
    print_substep "Sending monthly trends to Claude AI..."
    
    # Load and process monthly changelog prompt template
    local monthly_template=$(load_prompt "monthly-changelog")
    local monthly_prompt=$(process_template "$monthly_template" "commits" "$monthly_commits")
    
    local monthly_content=$(claude --print "$monthly_prompt" 2>&1)
    
    # Check for errors
    if [[ "$monthly_content" == *"error"* ]] || [[ "$monthly_content" == *"Error"* ]] || [ -z "$monthly_content" ]; then
        print_error "Claude AI failed for monthly changelog, creating fallback..."
        local monthly_file="changelogs/monthly-changelog.md"
        echo "# Monthly Development Overview" > "$monthly_file"
        echo "" >> "$monthly_file"
        echo "A summary of recent monthly development from $first_date to $last_date." >> "$monthly_file"
        echo "" >> "$monthly_file"
        echo "## Recent Monthly Activity" >> "$monthly_file"
        echo "" >> "$monthly_file"
        git log --pretty=format:"- %ad: %s" --date=format:'%Y-%m' -n 40 >> "$monthly_file"
        print_verbose "Fallback monthly summary created"
    else
        print_substep "Processing monthly overview response..."
        local monthly_content_length=$(echo "$monthly_content" | wc -l | tr -d ' ')
        print_verbose "Claude generated ${monthly_content_length} lines of monthly overview"
        
        print_substep "Writing strategic monthly overview..."
        local monthly_file="changelogs/monthly-changelog.md"
        echo "# Monthly Development Overview" > "$monthly_file"
        echo "" >> "$monthly_file"
        echo "A strategic summary of monthly development achievements from $first_date to $last_date." >> "$monthly_file"
        echo "" >> "$monthly_file"
        echo "$monthly_content" >> "$monthly_file"
        
        local monthly_file_size=$(wc -c < "$monthly_file")
        print_verbose "Monthly overview saved (${monthly_file_size} bytes)"
    fi
    
    print_step "✅ Changelog generation complete!"
    print_success "Intelligent daily summary: $daily_file"
    print_success "Intelligent weekly summary: $weekly_file" 
    print_success "Intelligent monthly overview: $monthly_file"
    
    print_step "📊 Final statistics and summary..."
    print_substep "Calculating generation metrics..."
    local total_file_size=$(($(wc -c < CHANGELOG.md) + $daily_file_size + $weekly_file_size + $monthly_file_size))
    local avg_commits_per_day=$((total_commits / unique_days))
    
    printf "${YELLOW}📊 Changelog Generation Results:${NC}\n"
    print_verbose "Analysis scope:"
    printf "  ├─ Total commits analyzed: ${total_commits}\n"
    printf "  ├─ Date range: ${first_date} to ${last_date}\n"
    printf "  ├─ Active development days: ${unique_days}\n"
    printf "  └─ Average commits per day: ${avg_commits_per_day}\n"
    print_verbose "Output files:"
    printf "  ├─ Main CHANGELOG.md ($(wc -c < CHANGELOG.md) bytes)\n"
    printf "  ├─ Daily summary (${daily_file_size} bytes)\n"
    printf "  ├─ Weekly summary (${weekly_file_size} bytes)\n"
    printf "  ├─ Monthly overview (${monthly_file_size} bytes)\n"
    printf "  └─ Total content generated: ${total_file_size} bytes\n"
    
    print_verbose "AI-powered changelog generation workflow completed successfully"
}

# Help command
cmd_help() {
    print_header "AI-Powered Development Toolkit"
    print_verbose "Displaying comprehensive command reference and usage guide..."
    
    printf "${PURPLE}🔮 SuperClaude - Your AI Development Assistant${NC}\n\n"
    printf "${YELLOW}📋 Available Commands:${NC}\n\n"
    
    printf "  ${BLUE}commit${NC}     - 🤖 Generate AI-powered commit messages and push\n"
    printf "              ${BLUE}├─${NC} Analyzes git changes with detailed context\n"
    printf "              ${BLUE}├─${NC} Creates conventional commit messages\n"
    printf "              ${BLUE}├─${NC} Optional: provide additional context: commit \"fixing auth bug\"\n"
    printf "              ${BLUE}├─${NC} Interactive mode: confirm/edit before committing\n"
    printf "              ${BLUE}└─${NC} Automatically stages, commits, and pushes\n\n"
    
    printf "  ${BLUE}changelog${NC}  - 📅 Generate intelligent changelog from commit history\n"
    printf "              ${BLUE}├─${NC} Creates human-readable summaries (not raw commits)\n"
    printf "              ${BLUE}├─${NC} Generates daily, weekly, and monthly overviews\n"
    printf "              ${BLUE}└─${NC} Filters trivial changes, focuses on user impact\n\n"
    
    printf "  ${BLUE}readme${NC}     - 📖 Generate comprehensive README.md\n"
    printf "              ${BLUE}├─${NC} Analyzes codebase structure and dependencies\n"
    printf "              ${BLUE}├─${NC} Creates professional documentation\n"
    printf "              ${BLUE}└─${NC} Includes installation, usage, and examples\n\n"
    
    printf "  ${BLUE}review${NC}     - 🔍 Perform deep code review and analysis\n"
    printf "              ${BLUE}├─${NC} Security vulnerability assessment\n"
    printf "              ${BLUE}├─${NC} Code quality and maintainability analysis\n"
    printf "              ${BLUE}└─${NC} Actionable improvement recommendations\n\n"
    
    printf "  ${BLUE}brainstorm${NC} - 💡 Brainstorm improvement ideas and features\n"
    printf "              ${BLUE}├─${NC} Analyzes current codebase capabilities\n"
    printf "              ${BLUE}├─${NC} Suggests new features and optimizations\n"
    printf "              ${BLUE}└─${NC} Identifies growth opportunities\n\n"
    
    printf "  ${BLUE}docs${NC}       - 📚 Generate technical documentation\n"
    printf "              ${BLUE}├─${NC} Creates comprehensive technical guides\n"
    printf "              ${BLUE}├─${NC} Documents architecture and components\n"
    printf "              ${BLUE}└─${NC} Includes deployment and troubleshooting\n\n"
    
    printf "  ${BLUE}annotate${NC}   - 📝 Generate AI-powered commit annotations\n"
    printf "              ${BLUE}├─${NC} Adds notes to commit history\n"
    printf "              ${BLUE}└─${NC} Helps understand code changes\n\n"
    
    printf "  ${BLUE}help${NC}       - ❓ Show this comprehensive help message\n\n"
    
    printf "  ${BLUE}version${NC}    - 📋 Show version and system information\n\n"
    
    printf "${YELLOW}🔮 Usage Patterns:${NC}\n"
    printf "  ${GREEN}yarn superclaude <command> [flags]${NC}  # Full command name\n"
    printf "  ${GREEN}yarn superclaude:<command>${NC}          # Quick yarn shortcut\n"
    printf "  ${GREEN}yarn superclaude:<command>:verbose${NC}  # Verbose yarn shortcut\n"
    printf "  ${GREEN}./scripts/superclaude.sh <command> -v${NC} # Direct with verbose flag\n\n"
    
    printf "${YELLOW}🏁 Flags:${NC}\n"
    printf "  ${GREEN}--interactive, -i${NC}   # Interactive mode for commit confirmation\n"
    printf "  ${GREEN}--verbose, -v${NC}       # Verbose mode for detailed output\n"
    printf "  ${GREEN}--verify${NC}            # Force full dependency verification (bypass cache)\n"
    printf "  ${GREEN}--version${NC}           # Show version and system information\n\n"
    
    printf "${YELLOW}📝 Examples:${NC}\n"
    printf "  ${GREEN}yarn superclaude:commit${NC}            # Quick AI commit (quiet mode)\n"
    printf "  ${GREEN}yarn superclaude:commit:verbose${NC}    # Detailed progress output\n"
    printf "  ${GREEN}yarn superclaude:commit:interactive${NC} # Interactive confirmation\n"
    printf "  ${GREEN}yarn superclaude:commit:full${NC}       # Interactive + verbose\n"
    printf "  ${GREEN}superclaude commit \"fixing auth bug\"${NC} # With additional context\n"
    printf "  ${GREEN}superclaude commit \"add user dashboard\" -i${NC} # Context + interactive\n"
    printf "  ${GREEN}yarn superclaude:annotate${NC}          # Add AI notes to all commits\n"
    printf "  ${GREEN}yarn superclaude:annotate:verbose${NC}  # Verbose annotation process\n"
    printf "  ${GREEN}yarn superclaude:changelog:verbose${NC} # Changelog with progress details\n"
    printf "  ${GREEN}./scripts/superclaude.sh readme -v${NC} # Direct call with verbose flag\n\n"
    
    printf "${YELLOW}💡 Tips:${NC}\n"
    printf "  ${BLUE}├─${NC} Use -v/--verbose for detailed step-by-step progress\n"
    printf "  ${BLUE}├─${NC} Default mode shows only main steps and results\n"
    printf "  ${BLUE}├─${NC} Use -i/--interactive for commit confirmation and editing\n"
    printf "  ${BLUE}├─${NC} Claude AI analyzes your code context for better results\n"
    printf "  ${BLUE}├─${NC} Generated content is human-readable and professional\n"
    printf "  ${BLUE}└─${NC} Use in any git repository for instant AI assistance\n\n"
    
    print_verbose "Help system displayed successfully"
}

# Version command
cmd_version() {
    print_header "Version Information"
    
    printf "${BLUE}SuperClaude Version:${NC} ${GREEN}v${SUPERCLAUDE_VERSION}${NC}\n\n"
    
    printf "${YELLOW}🔧 System Information:${NC}\n"
    
    # Show tool versions
    if command -v claude >/dev/null 2>&1; then
        local claude_version=$(claude --version 2>/dev/null | head -1 || echo "unknown")
        printf "  ├─ Claude Code: ${claude_version}\n"
    else
        printf "  ├─ Claude Code: ${RED}not installed${NC}\n"
    fi
    
    if command -v git >/dev/null 2>&1; then
        local git_version=$(git --version | cut -d' ' -f3)
        printf "  ├─ Git: ${git_version}\n"
    else
        printf "  ├─ Git: ${RED}not installed${NC}\n"
    fi
    
    if command -v node >/dev/null 2>&1; then
        local node_version=$(node --version)
        printf "  ├─ Node.js: ${node_version}\n"
    else
        printf "  ├─ Node.js: ${RED}not installed${NC}\n"
    fi
    
    if command -v gh >/dev/null 2>&1; then
        local gh_version=$(gh --version | head -1 | cut -d' ' -f3)
        printf "  └─ GitHub CLI: ${gh_version}\n"
    else
        printf "  └─ GitHub CLI: ${RED}not installed${NC}\n"
    fi
    
    echo ""
    
    # Check for updates
    printf "${YELLOW}📦 Checking for updates...${NC}\n"
    
    local latest_version=""
    if command -v timeout >/dev/null 2>&1; then
        latest_version=$(timeout 5s npm view superclaude version 2>/dev/null || echo "")
    else
        latest_version=$(npm view superclaude version 2>/dev/null || echo "")
    fi
    
    if [ -n "$latest_version" ]; then
        if [ "$latest_version" != "$SUPERCLAUDE_VERSION" ]; then
            printf "${YELLOW}  ├─ Current: v${SUPERCLAUDE_VERSION}${NC}\n"
            printf "${GREEN}  ├─ Latest:  v${latest_version}${NC}\n"
            printf "${YELLOW}  └─ Update:  ${GREEN}npm install -g superclaude@latest${NC}\n"
        else
            printf "${GREEN}  └─ You're running the latest version! 🎉${NC}\n"
        fi
    else
        printf "${RED}  └─ Unable to check for updates${NC}\n"
    fi
    
    echo ""
    printf "${BLUE}📚 More info: ${NC}https://github.com/gwendall/superclaude\n"
}

# Main command router
case "$COMMAND" in
    "commit")
        cmd_commit
        ;;
    "readme")
        cmd_readme
        ;;
    "review")
        cmd_review
        ;;
    "brainstorm")
        cmd_brainstorm
        ;;
    "docs")
        cmd_docs
        ;;
    "changelog")
        cmd_changelog
        ;;
    "annotate")
        cmd_annotate
        ;;
    "version"|"--version")
        cmd_version
        ;;
    "verify"|"--verify")
        check_dependencies --verify
        ;;
    "help"|"--help"|"-h"|"")
        cmd_help
        ;;
    *)
        print_error "Unknown command: $COMMAND"
        echo ""
        cmd_help
        exit 1
        ;;
esac 