#!/bin/bash
# KB Status — mark raw files as absorbed or skipped
# Usage: ./scripts/status.sh absorb <path>   or   ./scripts/status.sh skip <path>

set -euo pipefail

KB_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$KB_DIR"

if [ $# -lt 2 ]; then
    echo "Usage: ./scripts/status.sh <absorb|skip|inbox> <path-to-raw-file>" >&2
    echo "" >&2
    echo "Examples:" >&2
    echo "  ./scripts/status.sh absorb raw/2026-07/2026-07-13-article.md" >&2
    echo "  ./scripts/status.sh skip raw/2026-07/2026-07-13-old-news.md" >&2
    echo "  ./scripts/status.sh inbox raw/2026-07/file.md   # reset to inbox" >&2
    exit 1
fi

ACTION="$1"
FILE="$2"

case "$ACTION" in
    absorb|skip|inbox) ;;
    *)
        echo "Error: action must be 'absorb', 'skip', or 'inbox'" >&2
        exit 1 ;;
esac

if [ ! -f "$FILE" ]; then
    echo "Error: file not found: $FILE" >&2
    exit 1
fi

# Check it's a raw file
if [[ "$FILE" != raw/* ]]; then
    echo "Error: only raw/ files can have status changed (not wiki/)" >&2
    exit 1
fi

# Update the status line in frontmatter
if grep -q '^status:' "$FILE"; then
    sed -i "s/^status:.*/status: ${ACTION}/" "$FILE"
else
    # No status field — add after the first --- line
    sed -i "0,/^---$/s//---\nstatus: ${ACTION}/" "$FILE"
fi

echo "✅ $FILE → status: ${ACTION}"

# Append to log.md
TIMESTAMP=$(date +%Y-%m-%d)
TITLE=$(awk '/^---/{f++;next} f==1 && /^title:/{gsub(/^title: *"?/,""); gsub(/"$/,""); print; exit}' "$FILE" 2>/dev/null || basename "$FILE" .md)
echo "## [${TIMESTAMP}] ${ACTION} | ${TITLE}" >> log.md
echo "  - ${FILE}" >> log.md
echo "📝 Logged to log.md"
