#!/usr/bin/env bash
# Caveman + RTK Wrapper - Automated token-efficient output formatting
# Installed automatically via homelab-context post-pull hook
# Source: https://github.com/adityahimaone/hermes-agent-rtk-caveman
# Usage: caveman_wrapper.sh <workflow> [options]

set -e

WORKFLOW="$1"
shift

CAVEMAN=~/bin/caveman
TEMPLATES_DIR=~/templates
DATA_DIR=/tmp/caveman_data

mkdir -p "$DATA_DIR"

case "$WORKFLOW" in
  git-status)
    git status --porcelain | awk '
    BEGIN { staged=0; modified=0; untracked=0; deleted=0 }
    /^[MARC]./ { staged_arr[staged++] = substr($0, 4) }
    /^.[MARC]/ { modified_arr[modified++] = substr($0, 4) }
    /^\?\?/ { untracked_arr[untracked++] = substr($0, 4) }
    /^D/ || /^.D/ { deleted_arr[deleted++] = substr($0, 4) }
    END {
      printf "{"
      printf "\"staged\":["
      for(i=0;i<staged;i++) printf "%s\"%s\"", (i>0?",":""), staged_arr[i]
      printf "],\"modified\":["
      for(i=0;i<modified;i++) printf "%s\"%s\"", (i>0?",":""), modified_arr[i]
      printf "],\"untracked\":["
      for(i=0;i<untracked;i++) printf "%s\"%s\"", (i>0?",":""), untracked_arr[i]
      printf "],\"deleted\":["
      for(i=0;i<deleted;i++) printf "%s\"%s\"", (i>0?",":""), deleted_arr[i]
      printf "]}"
    }' > "$DATA_DIR/git_status.json"

    if command -v rtk &>/dev/null; then
      rtk "$CAVEMAN" "$TEMPLATES_DIR/git_status.txt" "$DATA_DIR/git_status.json"
    else
      node "$CAVEMAN" "$TEMPLATES_DIR/git_status.txt" "$DATA_DIR/git_status.json"
    fi
    ;;

  git-log)
    LIMIT="${1:-10}"
    git log --oneline -"$LIMIT" --format='{"hash":"%h","author":"%an","date":"%ad","message":"%s"}' --date=short | \
      jq -s '.' > "$DATA_DIR/git_log.json"
    jq '{commits: .}' "$DATA_DIR/git_log.json" > "$DATA_DIR/git_log_final.json"
    if command -v rtk &>/dev/null; then
      rtk "$CAVEMAN" "$TEMPLATES_DIR/git_log.txt" "$DATA_DIR/git_log_final.json"
    else
      node "$CAVEMAN" "$TEMPLATES_DIR/git_log.txt" "$DATA_DIR/git_log_final.json"
    fi
    ;;

  test-results)
    TEST_CMD="${1:-npx vitest run}"
    $TEST_CMD --reporter json 2>/dev/null | \
      jq '{total: .numTotalTests, passed: .numPassedTests, failed: .numFailedTests, suites: [.testResults[] | {name: .name, status: .status, duration: .duration}]}' > "$DATA_DIR/test_results.json" || true
    if command -v rtk &>/dev/null; then
      rtk "$CAVEMAN" "$TEMPLATES_DIR/test_results.txt" "$DATA_DIR/test_results.json"
    else
      node "$CAVEMAN" "$TEMPLATES_DIR/test_results.txt" "$DATA_DIR/test_results.json"
    fi
    ;;

  *)
    echo "Usage: caveman_wrapper.sh <workflow> [options]"
    echo "  git-status            - Compact git status"
    echo "  git-log [limit]       - Recent git commits"
    echo "  test-results [cmd]    - Compact test results"
    exit 1
    ;;
esac