#!/usr/bin/env bash
set -euo pipefail

# Find related worklogs by keyword search (OR semantics)
# Usage: find-related-logs.sh "keyword1 keyword2"

if [ $# -eq 0 ]; then
    echo "Usage: $0 \"keyword1 keyword2 ...\""
    echo "Searches previous worklogs for keywords (OR logic)"
    exit 1
fi

# Get repository root to handle relative paths correctly
if git rev-parse --git-dir > /dev/null 2>&1; then
    REPO_ROOT=$(git rev-parse --show-toplevel)
    WORKLOG_DIR="$REPO_ROOT/docs/worklogs"
else
    # Not in a git repo, try relative path as fallback
    WORKLOG_DIR="docs/worklogs"
fi

# Check if worklog directory exists
if [ ! -d "$WORKLOG_DIR" ]; then
    echo "Worklog directory not found: $WORKLOG_DIR"
    exit 1
fi

# Split keywords into array for OR search
read -ra KEYWORD_ARRAY <<< "$*"

# Search for keywords in worklogs with OR semantics
echo "Searching for: ${KEYWORD_ARRAY[*]} (OR logic)"
echo "---"

# Use ripgrep if available, otherwise fall back to grep
# Note: rg/grep return non-zero when no matches, so we need '|| true' to prevent errexit
if command -v rg &> /dev/null; then
    # Build ripgrep pattern: keyword1|keyword2|keyword3
    PATTERN=$(IFS='|'; echo "${KEYWORD_ARRAY[*]}")
    RESULTS=$(rg -i -l "$PATTERN" "$WORKLOG_DIR" 2>/dev/null | sort -r | head -10 || true)
else
    # Build grep command with multiple -e flags for OR logic
    GREP_ARGS=()
    for keyword in "${KEYWORD_ARRAY[@]}"; do
        GREP_ARGS+=(-e "$keyword")
    done
    RESULTS=$(grep -r -i -l "${GREP_ARGS[@]}" "$WORKLOG_DIR" 2>/dev/null | sort -r | head -10 || true)
fi

# Check if we found any results
if [ -z "$RESULTS" ]; then
    echo "No related worklogs found for: ${KEYWORD_ARRAY[*]}"
    exit 0
fi

# Display results
echo "$RESULTS" | while read -r file; do
    # Extract title and date from file (supports both markdown YAML frontmatter and legacy org-mode)
    if grep -q "^---$" "$file" 2>/dev/null; then
        # Markdown YAML frontmatter
        TITLE=$(grep -m1 "^title:" "$file" 2>/dev/null | sed 's/title: *"\?\([^"]*\)"\?/\1/' || echo "Untitled")
        DATE=$(grep -m1 "^date:" "$file" 2>/dev/null | sed 's/date: *//' || echo "Unknown date")
        KEYWORDS_LINE=$(grep -m1 "^keywords:" "$file" 2>/dev/null | sed 's/keywords: *//' || echo "")
    else
        # Legacy org-mode format
        TITLE=$(grep -m1 "^#+TITLE:" "$file" 2>/dev/null | sed 's/#+TITLE: //' || echo "Untitled")
        DATE=$(grep -m1 "^#+DATE:" "$file" 2>/dev/null | sed 's/#+DATE: //' || echo "Unknown date")
        KEYWORDS_LINE=$(grep -m1 "^#+KEYWORDS:" "$file" 2>/dev/null | sed 's/#+KEYWORDS: //' || echo "")
    fi

    echo "File: $file"
    echo "  Title: $TITLE"
    echo "  Date: $DATE"
    echo "  Keywords: $KEYWORDS_LINE"
    echo ""
done
