#!/bin/bash
# Update time-based symlinks based on worktree modification times
# Usage: ./workflow/refresh

WORKTREE_BASE="worktrees"
NOW=$(date +%s)
HOUR=3600
DAY=$((HOUR * 24))
WEEK=$((DAY * 7))

# Directory names for time buckets
DIR_24H="last-24-hours"
DIR_48H="last-48-hours"
DIR_WEEK="last-week"

# Ensure directories exist
mkdir -p "$WORKTREE_BASE/$DIR_24H" "$WORKTREE_BASE/$DIR_48H" "$WORKTREE_BASE/$DIR_WEEK"

# Create convenience symlinks (today -> last-24-hours, etc.)
ln -sfn "$DIR_24H" "$WORKTREE_BASE/today"
ln -sfn "$DIR_48H" "$WORKTREE_BASE/yesterday"
ln -sfn "$DIR_WEEK" "$WORKTREE_BASE/week"

# Clear existing symlinks in time directories
find "$WORKTREE_BASE/$DIR_24H" -type l -delete 2>/dev/null
find "$WORKTREE_BASE/$DIR_48H" -type l -delete 2>/dev/null
find "$WORKTREE_BASE/$DIR_WEEK" -type l -delete 2>/dev/null

# Find all worktrees in dated directories (YYYYMMDD pattern)
for dated_dir in "$WORKTREE_BASE"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]; do
    [[ -d "$dated_dir" ]] || continue

    for worktree in "$dated_dir"/*/; do
        [[ -d "$worktree" ]] || continue

        NAME=$(basename "$worktree")
        DATE_DIR=$(basename "$dated_dir")

        # Get most recent modification time in worktree
        # Check STATUS.md first, then fall back to directory mtime
        if [[ -f "$worktree/STATUS.md" ]]; then
            MTIME=$(stat -c %Y "$worktree/STATUS.md" 2>/dev/null || stat -f %m "$worktree/STATUS.md" 2>/dev/null)
        else
            MTIME=$(stat -c %Y "$worktree" 2>/dev/null || stat -f %m "$worktree" 2>/dev/null)
        fi

        AGE=$((NOW - MTIME))
        REL_PATH="../$DATE_DIR/$NAME"

        # Create OVERLAPPING symlinks based on age
        # A worktree active 12h ago appears in all three
        if [[ $AGE -lt $DAY ]]; then
            # Last 24 hours
            ln -sf "$REL_PATH" "$WORKTREE_BASE/$DIR_24H/$NAME"
        fi

        if [[ $AGE -lt $((DAY * 2)) ]]; then
            # Last 48 hours (overlaps with 24h)
            ln -sf "$REL_PATH" "$WORKTREE_BASE/$DIR_48H/$NAME"
        fi

        if [[ $AGE -lt $WEEK ]]; then
            # Last 7 days (overlaps with both)
            ln -sf "$REL_PATH" "$WORKTREE_BASE/$DIR_WEEK/$NAME"
        fi
    done
done

# Count results
COUNT_24H=$(find "$WORKTREE_BASE/$DIR_24H" -type l 2>/dev/null | wc -l)
COUNT_48H=$(find "$WORKTREE_BASE/$DIR_48H" -type l 2>/dev/null | wc -l)
COUNT_WEEK=$(find "$WORKTREE_BASE/$DIR_WEEK" -type l 2>/dev/null | wc -l)

echo "Symlinks refreshed: last-24-hours=$COUNT_24H, last-48-hours=$COUNT_48H, last-week=$COUNT_WEEK"
