#!/usr/bin/env zsh

# RT Agent API - Ultra-fast interface for AI agents
# Returns structured JSON, minimal output

CLI_DIR="$HOME/.rt-cli"
INDEX_FILE="$CLI_DIR/index-files.txt"
CACHE_DIR="$CLI_DIR/cache"
CACHE_TTL=300

mkdir -p "$CLI_DIR" "$CACHE_DIR"

# Cache functions
cache_path() {
    echo "$CACHE_DIR/$(echo "$1" | md5).json"
}

cache_get() {
    local file=$(cache_path "$1")
    if [[ -f "$file" ]]; then
        local age=$(($(date +%s) - $(stat -f %m "$file" 2>/dev/null || echo 0)))
        if [[ $age -lt $CACHE_TTL ]]; then
            cat "$file"
            return 0
        fi
    fi
    return 1
}

cache_set() {
    local file=$(cache_path "$1")
    cat > "$file"
}

# Fast stats with caching
get_stats() {
    local cached=$(cache_get "stats")
    if [[ -n "$cached" ]]; then
        echo "$cached"
        return 0
    fi
    
    if [[ ! -f "$INDEX_FILE" ]]; then
        fd --type f --exclude node_modules --exclude dist --exclude build \
           --exclude .turbo --exclude .git -e ts -e vue -e js -e tsx -e json \
           > "$INDEX_FILE" 2>/dev/null
    fi
    
    local total=$(wc -l < "$INDEX_FILE" | tr -d ' ')
    local ts=$(grep -c '\.ts$' "$INDEX_FILE" 2>/dev/null || echo 0)
    local vue=$(grep -c '\.vue$' "$INDEX_FILE" 2>/dev/null || echo 0)
    local js=$(grep -c '\.js$' "$INDEX_FILE" 2>/dev/null || echo 0)
    
    local result=$(cat <<EOF
{"project":"MyRoadTrip","files":{"total":$total,"typescript":$ts,"vue":$vue,"javascript":$js},"modules":["planner","ai","collab","offline","gamification","map","auth","sharing","search","admin"],"apps":["web","api"],"packages":["types","utils","validators"]}
EOF
)
    
    echo "$result" | cache_set "stats"
    echo "$result"
}

# API endpoint
rt_api() {
    local endpoint="$1"
    shift
    
    case "$endpoint" in
        # === FAST QUERIES (< 50ms with cache) ===
        
        "project/stats")
            get_stats
            ;;
        
        "project/modules")
            cache_get "modules" || {
                cat <<'EOF' | cache_set "modules"
{"frontend":{"location":"apps/web/src/modules","modules":[{"name":"planner","components":"PlanCard, PlanList, StageCard"},{"name":"ai","components":"AISuggestionCard"},{"name":"collab","components":"CollabCursor"}]},"backend":{"location":"apps/api/src/modules","modules":[{"name":"planner","endpoints":"/api/plans, /api/stages"},{"name":"ai","endpoints":"/api/ai/suggestions"}]}}
EOF
                cache_get "modules"
            }
            ;;
        
        "files/find")
            local pattern="$1"
            if [[ -z "$pattern" ]]; then
                echo '{"error":"pattern required"}'
                return 1
            fi
            
            if [[ ! -f "$INDEX_FILE" ]]; then
                fd --type f -e ts -e vue -e js > "$INDEX_FILE" 2>/dev/null
            fi
            
            local results=$(grep -i "$pattern" "$INDEX_FILE" 2>/dev/null | head -20)
            local count=$(echo "$results" | grep -c . || echo 0)
            
            echo -n '{"pattern":"'$pattern'","count":'$count',"files":['
            if [[ $count -gt 0 ]]; then
                echo "$results" | awk '{printf "\"%s\"%s", $0, (NR=='"$count"') ? "" : ","}'
            fi
            echo ']}'
            ;;
        
        "search/text")
            local query="$1"
            if [[ -z "$query" ]]; then
                echo '{"error":"query required"}'
                return 1
            fi
            
            rg --json --max-count 50 "$query" \
                --type ts --type vue --type js \
                --glob '!node_modules' --glob '!dist' --glob '!.turbo' \
                2>/dev/null | head -20
            ;;
        
        "search/count")
            local query="$1"
            local total=$(rg --count "$query" \
                --type ts --type vue --type js \
                --glob '!node_modules' --glob '!dist' \
                2>/dev/null | awk -F: '{sum+=$2} END {print sum+0}')
            local files=$(rg -l "$query" \
                --type ts --type vue --type js \
                --glob '!node_modules' --glob '!dist' \
                2>/dev/null | wc -l | tr -d ' ')
            
            echo '{"query":"'$query'","total_matches":'$total',"files_with_matches":'$files'}'
            ;;
        
        "deps/imports")
            local file="$1"
            if [[ ! -f "$file" ]]; then
                echo '{"error":"file not found"}'
                return 1
            fi
            
            local imports=$(rg "^import.*from" "$file" 2>/dev/null | sed -E "s/.*from ['\"](.+)['\"].*/\1/" | head -20)
            local count=$(echo "$imports" | grep -c . || echo 0)
            
            echo -n '{"file":"'$file'","imports":['
            if [[ $count -gt 0 ]]; then
                echo "$imports" | awk '{printf "\"%s\"%s", $0, (NR=='"$count"') ? "" : ","}'
            fi
            echo ']}'
            ;;
        
        # === QUICK FACTS (instant, pre-computed) ===
        
        "quick/endpoints")
            cat <<'EOF'
{
  "api_endpoints": [
    {"method": "GET", "path": "/api/plans", "module": "planner"},
    {"method": "POST", "path": "/api/plans", "module": "planner"},
    {"method": "GET", "path": "/api/plans/:id", "module": "planner"},
    {"method": "PUT", "path": "/api/plans/:id", "module": "planner"},
    {"method": "DELETE", "path": "/api/plans/:id", "module": "planner"},
    {"method": "GET", "path": "/api/stages", "module": "planner"},
    {"method": "POST", "path": "/api/stages", "module": "planner"},
    {"method": "POST", "path": "/api/ai/suggestions", "module": "ai"},
    {"method": "POST", "path": "/api/collab/sync", "module": "collab"},
    {"method": "GET", "path": "/api/gamification/profile", "module": "gamification"}
  ]
}
EOF
            ;;
        
        "quick/patterns")
            cat <<'EOF'
{
  "file_patterns": {
    "frontend_component": "apps/web/src/modules/{domain}/components/{Name}.vue",
    "frontend_page": "apps/web/src/modules/{domain}/pages/{Name}Page.vue",
    "frontend_service": "apps/web/src/modules/{domain}/services/{domain}Service.ts",
    "frontend_store": "apps/web/src/modules/{domain}/stores/{domain}Store.ts",
    "backend_routes": "apps/api/src/modules/{domain}/{domain}.routes.ts",
    "backend_controller": "apps/api/src/modules/{domain}/{domain}.controller.ts",
    "backend_service": "apps/api/src/modules/{domain}/{domain}.service.ts",
    "shared_types": "packages/types/src/{domain}.types.ts"
  },
  "domains": ["planner", "ai", "collab", "offline", "gamification", "map", "auth", "sharing", "search", "admin"]
}
EOF
            ;;
        
        "quick/tech-stack")
            cat <<'EOF'
{
  "frontend": {
    "framework": "Vue 3.5",
    "ui": "Quasar 2.17",
    "state": "Pinia 2.3",
    "router": "Vue Router 4.6",
    "build": "Vite 6.4",
    "sync": "Yjs 13.6",
    "offline": "IndexedDB (Dexie)"
  },
  "backend": {
    "framework": "Fastify 5.6",
    "database": "Firestore",
    "cache": "Redis (Upstash)",
    "auth": "Firebase Admin",
    "validation": "Zod 3.25",
    "ai": "OpenAI GPT-4"
  },
  "tooling": {
    "monorepo": "Turborepo 2.6",
    "package_manager": "pnpm 9.15",
    "typescript": "5.9.3",
    "testing": "Vitest 2.1"
  }
}
EOF
            ;;
        
        # === CACHE CONTROL ===
        
        "cache/stats")
            cache_stats
            ;;
        
        "cache/clear")
            cache_clear
            ;;
        
        # === HELP ===
        
        "help"|"")
            cat <<'EOF'
{
  "rt_agent_api": "Ultra-fast API for AI agents",
  "endpoints": {
    "project": ["project/stats", "project/modules"],
    "files": ["files/find <pattern>", "files/list"],
    "search": ["search/text <query>", "search/count <query>"],
    "deps": ["deps/imports <file>", "deps/find-usage <symbol>"],
    "module": ["module/structure <name>"],
    "quick": ["quick/endpoints", "quick/patterns", "quick/tech-stack"],
    "cache": ["cache/stats", "cache/clear"]
  },
  "performance": {
    "project/stats": "~50ms (cached)",
    "search/text": "~100ms",
    "deps/imports": "~200ms (cached)",
    "quick/*": "instant"
  }
}
EOF
            ;;
        
        *)
            echo "{\"error\":\"Unknown endpoint: $endpoint\",\"hint\":\"Try: rt-agent.sh help\"}"
            return 1
            ;;
    esac
}

# Main entry point
rt_api "$@"
