#!/usr/bin/env zsh

# RoadTripper CLI - Fast project navigation and search
# Optimized for MyRoadTrip monorepo + AI Agents

CLI_DIR="$HOME/.rt-cli"
INDEX_FILE="$CLI_DIR/index-files.txt"
CACHE_DIR="$CLI_DIR/cache"
CONFIG="$CLI_DIR/config.json"
STATS_FILE="$CLI_DIR/stats.json"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Agent mode (compact output, no colors, JSON)
AGENT_MODE="${RT_AGENT_MODE:-0}"

# Ensure CLI directory exists
mkdir -p "$CLI_DIR"
mkdir -p "$CACHE_DIR"

# Function to index project files
rt_index() {
    if [[ "$AGENT_MODE" == "1" ]]; then
        # Agent mode: silent, just do it
        fd --type f \
            --exclude node_modules \
            --exclude dist \
            --exclude build \
            --exclude .turbo \
            --exclude .git \
            --exclude coverage \
            --exclude .next \
            -e ts -e vue -e js -e tsx -e json \
            > "$INDEX_FILE" 2>/dev/null
        
        local count=$(wc -l < "$INDEX_FILE")
        echo "{\"status\":\"ok\",\"files\":$count,\"path\":\"$INDEX_FILE\"}"
    else
        echo -e "${BLUE}Indexing project files...${NC}"
        fd --type f \
            --exclude node_modules \
            --exclude dist \
            --exclude build \
            --exclude .turbo \
            --exclude .git \
            --exclude coverage \
            --exclude .next \
            -e ts -e vue -e js -e tsx -e json \
            > "$INDEX_FILE"
        
        local count=$(wc -l < "$INDEX_FILE")
        echo -e "${GREEN}✓ Indexed $count files${NC}"
    fi
}

# Fast text search with ripgrep
rt_search() {
    local query="$1"
    if [[ -z "$query" ]]; then
        echo "Usage: rt search <query>"
        return 1
    fi
    
    if [[ "$AGENT_MODE" == "1" ]]; then
        # Agent mode: JSON output, limited results
        local results=$(rg --type-add 'vue:*.vue' \
           --type-add 'ts:*.ts' \
           --type ts --type vue --type js \
           --ignore-case \
           --no-heading \
           --smart-case \
           --max-count 50 \
           --json \
           "$query" \
           --glob '!node_modules' \
           --glob '!dist' \
           --glob '!build' \
           --glob '!.turbo' \
           --glob '!coverage' 2>/dev/null | head -100)
        
        if [[ -n "$results" ]]; then
            echo "$results"
        else
            echo "{\"type\":\"summary\",\"stats\":{\"matches\":0}}"
        fi
    else
        # Human mode: colored, full output
        rg --type-add 'vue:*.vue' \
           --type-add 'ts:*.ts' \
           --type ts --type vue --type js \
           --ignore-case \
           --color=always \
           --line-number \
           --no-heading \
           --smart-case \
           "$query" \
           --glob '!node_modules' \
           --glob '!dist' \
           --glob '!build' \
           --glob '!.turbo' \
           --glob '!coverage'
    fi
}

# Fuzzy file search with preview
rt_fsearch() {
    if ! command -v fzf &> /dev/null; then
        echo "fzf not installed. Install with: brew install fzf"
        return 1
    fi
    
    fd --type f \
        --exclude node_modules \
        --exclude dist \
        --exclude build \
        --exclude .turbo \
        --exclude .git \
        -e ts -e vue -e js -e tsx -e json | \
    fzf --preview 'bat --style=numbers --color=always {}' \
        --preview-window=right:60%
}

# Architecture overview
rt_arch() {
    echo -e "${BLUE}Project Architecture:${NC}\n"
    fd --type d --max-depth 3 \
        --exclude node_modules \
        --exclude dist \
        --exclude .turbo \
        --exclude .git \
        apps packages | \
    tree -L 3 -d --fromfile
}

# Jump to file with fuzzy matching
rt_jump() {
    if [[ ! -f "$INDEX_FILE" ]]; then
        echo "Index not found. Running rt index..."
        rt_index
    fi
    
    local file=$(cat "$INDEX_FILE" | fzf --preview 'bat --style=numbers --color=always {}')
    if [[ -n "$file" ]]; then
        code "$file"
    fi
}

# Benchmark search tools
rt_bench() {
    echo -e "${BLUE}Benchmarking search tools...${NC}\n"
    
    if command -v hyperfine &> /dev/null; then
        hyperfine --warmup 2 \
            'rg "import" --type ts' \
            'fd -e ts | xargs grep "import"' \
            'grep -r "import" --include="*.ts"'
    else
        echo "Install hyperfine for benchmarks: brew install hyperfine"
        
        echo "Testing ripgrep..."
        time rg "import" --type ts > /dev/null
        
        echo -e "\nTesting fd + grep..."
        time fd -e ts | xargs grep "import" > /dev/null
    fi
}

# Interactive agent mode
rt_agent() {
    echo -e "${GREEN}RoadTripper CLI Agent${NC}"
    echo "Commands: search, fsearch, index, jump, arch, bench, help, exit"
    
    while true; do
        echo -n "> "
        read -r cmd args
        
        case "$cmd" in
            search) rt_search "$args" ;;
            fsearch) rt_fsearch ;;
            index) rt_index ;;
            jump) rt_jump ;;
            arch) rt_arch ;;
            bench) rt_bench ;;
            help) rt_help ;;
            exit) break ;;
            *) echo "Unknown command: $cmd" ;;
        esac
    done
}

# Help
rt_help() {
    echo -e "${GREEN}RoadTripper CLI Commands:${NC}"
    echo "  rt arch        - Show project architecture"
    echo "  rt search X    - Fast text search with ripgrep"
    echo "  rt fsearch     - Fuzzy file search with preview"
    echo "  rt index       - Rebuild file index"
    echo "  rt jump        - Fuzzy jump to file in VSCode"
    echo "  rt bench       - Benchmark search tools"
    echo "  rt agent       - Interactive command mode"
    echo "  rt help        - Show this help"
    echo ""
    echo "${YELLOW}Agent-optimized commands (JSON output):${NC}"
    echo "  rt stats       - Project statistics (JSON)"
    echo "  rt find X      - Find files by pattern (JSON)"
    echo "  rt modules     - List all modules (JSON)"
    echo "  rt deps X      - Find dependencies of file (JSON)"
    echo "  rt count X     - Count occurrences (JSON)"
}

# Project statistics (agent-optimized)
rt_stats() {
    if [[ ! -f "$INDEX_FILE" ]]; then
        rt_index >/dev/null 2>&1
    fi
    
    local total_files=$(wc -l < "$INDEX_FILE")
    local ts_files=$(grep -c '\.ts$' "$INDEX_FILE" 2>/dev/null || echo 0)
    local vue_files=$(grep -c '\.vue$' "$INDEX_FILE" 2>/dev/null || echo 0)
    local js_files=$(grep -c '\.js$' "$INDEX_FILE" 2>/dev/null || echo 0)
    
    # Count lines of code (fast approximation)
    local total_loc=$(cat "$INDEX_FILE" | xargs wc -l 2>/dev/null | tail -1 | awk '{print $1}')
    
    cat <<EOF
{
  "project": "MyRoadTrip",
  "files": {
    "total": $total_files,
    "typescript": $ts_files,
    "vue": $vue_files,
    "javascript": $js_files
  },
  "loc": $total_loc,
  "modules": ["planner", "ai", "collab", "offline", "gamification", "map", "auth", "sharing", "search", "admin"],
  "apps": ["web", "api"],
  "packages": ["types", "utils", "validators"]
}
EOF
}

# Find files by pattern (agent-optimized)
rt_find() {
    local pattern="$1"
    if [[ -z "$pattern" ]]; then
        echo '{"error":"Usage: rt find <pattern>"}'
        return 1
    fi
    
    if [[ ! -f "$INDEX_FILE" ]]; then
        rt_index >/dev/null 2>&1
    fi
    
    local results=$(grep -i "$pattern" "$INDEX_FILE" 2>/dev/null)
    local count=$(echo "$results" | grep -c . || echo 0)
    
    echo "{"
    echo "  \"pattern\": \"$pattern\","
    echo "  \"count\": $count,"
    echo "  \"files\": ["
    
    if [[ $count -gt 0 ]]; then
        echo "$results" | head -50 | awk '{printf "    \"%s\"%s\n", $0, (NR==50 || NR=='"$count"') ? "" : ","}'
    fi
    
    echo "  ]"
    echo "}"
}

# List modules (agent-optimized)
rt_modules() {
    cat <<'EOF'
{
  "frontend": {
    "location": "apps/web/src/modules",
    "modules": [
      {"name": "planner", "components": "PlanCard, PlanList, StageCard, etc.", "services": "plannerService", "stores": "plannerStore"},
      {"name": "ai", "components": "AISuggestionCard", "services": "aiService", "stores": "aiStore"},
      {"name": "collab", "components": "CollabCursor", "services": "syncService", "stores": "collabStore"},
      {"name": "offline", "components": "OfflineIndicator", "services": "offlineService", "stores": "offlineStore"},
      {"name": "gamification", "components": "BadgeCard", "services": "gamificationService", "stores": "gamificationStore"},
      {"name": "map", "components": "MapView", "services": "mapService", "stores": "mapStore"},
      {"name": "auth", "components": "LoginForm", "services": "authService", "stores": "authStore"},
      {"name": "sharing", "components": "ShareDialog", "services": "sharingService", "stores": "sharingStore"}
    ]
  },
  "backend": {
    "location": "apps/api/src/modules",
    "modules": [
      {"name": "planner", "endpoints": "/api/plans, /api/stages", "files": "routes, controller, service, repository"},
      {"name": "ai", "endpoints": "/api/ai/suggestions", "files": "routes, controller, service"},
      {"name": "collab", "endpoints": "/api/collab/sync", "files": "routes, controller, service"},
      {"name": "gamification", "endpoints": "/api/gamification/*", "files": "routes, controller, service, repository"},
      {"name": "auth", "endpoints": "/api/auth/*", "files": "middleware, service"},
      {"name": "sharing", "endpoints": "/api/share/*", "files": "routes, controller, service"}
    ]
  }
}
EOF
}

# Find dependencies (agent-optimized)
rt_deps() {
    local file="$1"
    if [[ -z "$file" ]]; then
        echo '{"error":"Usage: rt deps <file>"}'
        return 1
    fi
    
    local imports=$(rg "^import.*from.*['\"]" "$file" 2>/dev/null | sed -E "s/.*from ['\"](.+)['\"].*/\1/")
    local count=$(echo "$imports" | grep -c . || echo 0)
    
    echo "{"
    echo "  \"file\": \"$file\","
    echo "  \"imports\": ["
    
    if [[ $count -gt 0 ]]; then
        echo "$imports" | awk '{printf "    \"%s\"%s\n", $0, (NR=='"$count"') ? "" : ","}'
    fi
    
    echo "  ],"
    
    # Find files that import this file
    local importers=$(rg -l "from ['\"].*$(basename "$file" | sed 's/\.[^.]*$//')" 2>/dev/null | head -20)
    local importer_count=$(echo "$importers" | grep -c . || echo 0)
    
    echo "  \"importedBy\": ["
    if [[ $importer_count -gt 0 ]]; then
        echo "$importers" | awk '{printf "    \"%s\"%s\n", $0, (NR=='"$importer_count"') ? "" : ","}'
    fi
    echo "  ]"
    echo "}"
}

# Count occurrences (agent-optimized)
rt_count() {
    local query="$1"
    if [[ -z "$query" ]]; then
        echo '{"error":"Usage: rt count <query>"}'
        return 1
    fi
    
    local total=$(rg "$query" --type ts --type vue --type js \
        --glob '!node_modules' --glob '!dist' --glob '!.turbo' \
        --count 2>/dev/null | awk -F: '{sum+=$2} END {print sum+0}')
    
    local files=$(rg "$query" --type ts --type vue --type js \
        --glob '!node_modules' --glob '!dist' --glob '!.turbo' \
        --files-with-matches 2>/dev/null | wc -l)
    
    echo "{"
    echo "  \"query\": \"$query\","
    echo "  \"total_matches\": $total,"
    echo "  \"files_with_matches\": $files"
    echo "}"
}

# Main command router
rt() {
    local cmd="$1"
    shift
    
    case "$cmd" in
        arch) rt_arch "$@" ;;
        search) rt_search "$@" ;;
        fsearch) rt_fsearch "$@" ;;
        index) rt_index "$@" ;;
        jump) rt_jump "$@" ;;
        bench) rt_bench "$@" ;;
        agent) rt_agent "$@" ;;
        stats) rt_stats "$@" ;;
        find) rt_find "$@" ;;
        modules) rt_modules "$@" ;;
        deps) rt_deps "$@" ;;
        count) rt_count "$@" ;;
        help|--help|-h) rt_help ;;
        *) 
            echo "Unknown command: $cmd"
            rt_help
            return 1
            ;;
    esac
}

# Export functions
export -f rt
export -f rt_search
export -f rt_fsearch
export -f rt_index
export -f rt_jump
export -f rt_arch
export -f rt_bench
export -f rt_agent
export -f rt_help

# If script is sourced, just export functions
# If executed directly, run the command
if [[ "${BASH_SOURCE[0]}" == "${0}" ]] || [[ "$ZSH_EVAL_CONTEXT" =~ :file$ ]]; then
    rt "$@"
fi
