#!/bin/bash
# KB Inbox — list raw files with status: inbox
# Usage: ./scripts/inbox.sh [--count] [--recent N] [--month YYYY-MM]

set -euo pipefail

KB_DIR="$(cd "$(dirname "$0")/.." && pwd)"
COUNT_ONLY=false
RECENT=0
MONTH=""

# Check dependencies
if ! command -v rg &>/dev/null; then
    echo "❌ ripgrep (rg) is required. Install: apt install ripgrep / brew install ripgrep" >&2
    exit 1
fi

while [ $# -gt 0 ]; do
    case $1 in
        --count)
            COUNT_ONLY=true ;;
        --recent)
            if [[ ! "${2-}" =~ ^[0-9]+$ ]]; then
                echo "Error: --recent requires a number" >&2
                exit 1
            fi
            RECENT="$2"; shift ;;
        --month)
            MONTH="$2"; shift ;;
        *)
            echo "Unknown option: $1" >&2
            echo "Usage: ./scripts/inbox.sh [--count] [--recent N] [--month YYYY-MM]" >&2
            exit 1 ;;
    esac
    shift
done

cd "$KB_DIR"

# Use frontmatter-only match: status: inbox in the YAML header
match_inbox() {
    rg -l --glob '*.md' '^status:\s*inbox\s*$' "$@"
}

if $COUNT_ONLY; then
    if [ -n "$MONTH" ]; then
        count=$(match_inbox "raw/${MONTH}/" 2>/dev/null | wc -l)
        echo "📥 Inbox ($MONTH): $count items pending"
    else
        count=$(match_inbox raw/ 2>/dev/null | wc -l)
        echo "📥 Inbox total: $count items pending"
    fi
    exit 0
fi

echo "📥 KB Inbox — pending review"
echo "============================"
echo ""

# Collect items safely
search_path="raw/"
[ -n "$MONTH" ] && search_path="raw/${MONTH}/"

mapfile -t items < <(match_inbox "$search_path" 2>/dev/null | sort -r)
if [ "$RECENT" -gt 0 ] && [ "${#items[@]}" -gt "$RECENT" ]; then
    items=("${items[@]:0:$RECENT}")
fi

if [ "${#items[@]}" -eq 0 ]; then
    echo "✅ No inbox items — all caught up!"
    exit 0
fi

for f in "${items[@]}"; do
    # Extract frontmatter fields
    title=$(awk '/^---/{f++;next} f==1 && /^title:/{gsub(/^title: *"?/,""); gsub(/"$/,""); print; exit}' "$f" 2>/dev/null)
    url=$(awk '/^---/{f++;next} f==1 && /^source_url:/{gsub(/^source_url: *"?/,""); gsub(/"$/,""); print; exit}' "$f" 2>/dev/null)
    ingested=$(awk '/^---/{f++;next} f==1 && /^ingested:/{gsub(/^ingested: */,""); print; exit}' "$f" 2>/dev/null)
    
    if [ -z "$title" ]; then
        title=$(basename "$f" .md | sed 's/^[0-9-]*//' | tr '-' ' ' | sed 's/^ *//')
    fi
    
    echo "[${ingested:-?}] 📄 ${title:0:80}"
    if [ -n "$url" ]; then
        echo "        🔗 ${url:0:100}"
    fi
    echo "        📁 $f"
    echo ""
done

echo "---"
echo "Total: ${#items[@]} inbox items"
