#!/usr/bin/env bash
# Memory system health check
# Usage: scripts/mem-doctor

set -euo pipefail

SKILL_NAME="axiom-sre"
PERSONAL_DIR="$HOME/.config/amp/memory/personal/$SKILL_NAME"
ORGS_DIR="$HOME/.config/amp/memory/orgs"

# Legacy path
LEGACY_DIR="$HOME/.config/amp/memory/$SKILL_NAME"

echo "=== Memory Doctor ==="
echo ""

ISSUES=0
WARNINGS=0

check_ok() {
  echo "✓ $1"
}

check_warn() {
  echo "⚠️  $1"
  WARNINGS=$((WARNINGS + 1))
}

check_fail() {
  echo "✗ $1"
  ISSUES=$((ISSUES + 1))
}

count_entries() {
  local dir="$1"
  local count=0
  if [[ -d "$dir/kb" ]]; then
    for f in "$dir/kb"/*.md; do
      [[ -f "$f" ]] || continue
      local c
      c=$(grep -c "^## M-" "$f" 2>/dev/null | tr -d '[:space:]' || echo "0")
      if [[ "$c" =~ ^[0-9]+$ ]]; then
        count=$((count + c))
      fi
    done
  fi
  echo "$count"
}

# --- Check personal tier ---
echo "Personal Tier:"
if [[ -d "$PERSONAL_DIR/kb" ]]; then
  entries=$(count_entries "$PERSONAL_DIR")
  check_ok "Exists at $PERSONAL_DIR ($entries entries)"
else
  check_fail "Not found at $PERSONAL_DIR"
  echo "   Run: scripts/setup"
fi

# --- Check for legacy path ---
if [[ -d "$LEGACY_DIR/kb" ]]; then
  check_warn "Legacy memory at $LEGACY_DIR (should migrate)"
  echo "   Run: scripts/setup (will auto-migrate)"
fi

echo ""

# --- Check org tiers ---
echo "Org Tiers:"
if [[ -d "$ORGS_DIR" ]]; then
  org_count=0
  for org_dir in "$ORGS_DIR"/*/; do
    [[ -d "$org_dir" ]] || continue
    org_name=$(basename "$org_dir")
    org_count=$((org_count + 1))
    
    if [[ -d "$org_dir/.git" ]]; then
      # Check for uncommitted changes
      uncommitted=$(cd "$org_dir" && git status --porcelain | wc -l | tr -d ' ')
      entries=$(count_entries "$org_dir/$SKILL_NAME")
      if [[ "$uncommitted" -gt 0 ]]; then
        check_warn "$org_name: $entries entries, $uncommitted uncommitted changes"
        echo "   Run: scripts/mem-share $org_name \"message\""
      else
        check_ok "$org_name: $entries entries (synced)"
      fi
    else
      entries=$(count_entries "$org_dir/$SKILL_NAME")
      check_warn "$org_name: local-only, no git ($entries entries)"
    fi
  done

  if [[ $org_count -eq 0 ]]; then
    check_warn "No orgs configured"
    echo "   Run: scripts/org-add <name> <git-repo-url>"
  fi
else
  check_warn "Orgs directory not found"
fi

echo ""

# --- Summary ---
echo "=== Summary ==="
if [[ $ISSUES -eq 0 && $WARNINGS -eq 0 ]]; then
  echo "✓ Memory system healthy"
  exit 0
elif [[ $ISSUES -eq 0 ]]; then
  echo "⚠️  $WARNINGS warning(s)"
  exit 0
else
  echo "✗ $ISSUES issue(s), $WARNINGS warning(s)"
  exit 1
fi
