#!/bin/bash
# Archive done issues from INDEX.md to ARCHIVE.md
# Run periodically via cron

set -e

ISSUES_DIR="/home/aria/.openclaw/workspace/agency/issues"
INDEX="$ISSUES_DIR/INDEX.md"
ARCHIVE="$ISSUES_DIR/ARCHIVE.md"

# Get current month header
MONTH_HEADER="## $(date +'%B %Y')"

# Temp files
TMP_DONE=$(mktemp)
TMP_INDEX=$(mktemp)
trap "rm -f $TMP_DONE $TMP_INDEX" EXIT

echo "🗄️  Scanning for done issues..."

# Extract done issues from Active Issues table
# Look for rows with "done" or "✅ done" status
ARCHIVED_COUNT=0

# Read INDEX.md and find done issues in the Active Issues table
while IFS= read -r line; do
    # Check if this is a table row with "done" status (case insensitive)
    if echo "$line" | grep -qiE '^\| *(ARIA|AGY|INFRA|CLOCK)-[0-9]+.*\| *done *\|'; then
        # Extract issue ID and title
        ID=$(echo "$line" | sed -E 's/^\| *([A-Z]+-[0-9]+).*/\1/')
        TITLE=$(echo "$line" | sed -E 's/^\| *[A-Z]+-[0-9]+ *\| *([^|]+) *\|.*/\1/' | sed 's/^ *//;s/ *$//')
        
        echo "  → Archiving: $ID - $TITLE"
        echo "| $ID | $TITLE | $(date +'%Y-%m-%d') | Resolved |" >> "$TMP_DONE"
        ((ARCHIVED_COUNT++)) || true
    fi
done < "$INDEX"

# Also check the Clocklane section for done items
while IFS= read -r line; do
    if echo "$line" | grep -qiE '^\| *CLOCK-[0-9]+.*\| *✅ *(done|deployed)'; then
        ID=$(echo "$line" | sed -E 's/^\| *([A-Z]+-[0-9]+).*/\1/')
        TITLE=$(echo "$line" | sed -E 's/^\| *[A-Z]+-[0-9]+ *\| *([^|]+) *\|.*/\1/' | sed 's/^ *//;s/ *$//')
        
        echo "  → Archiving: $ID - $TITLE"
        echo "| $ID | $TITLE | $(date +'%Y-%m-%d') | Deployed |" >> "$TMP_DONE"
        ((ARCHIVED_COUNT++)) || true
    fi
done < "$INDEX"

if [ $ARCHIVED_COUNT -eq 0 ]; then
    echo "✅ No done issues to archive."
    exit 0
fi

echo ""
echo "📦 Archiving $ARCHIVED_COUNT issue(s)..."

# Update ARCHIVE.md - add entries under current month
if grep -q "$MONTH_HEADER" "$ARCHIVE"; then
    # Month header exists, insert after it
    # Find the line number of the month header and insert after the table header
    awk -v month="$MONTH_HEADER" -v done="$(cat $TMP_DONE)" '
        $0 == month { print; found=1; next }
        found && /^\| *—/ { print; print done; found=0; next }
        { print }
    ' "$ARCHIVE" > "$TMP_INDEX"
    mv "$TMP_INDEX" "$ARCHIVE"
else
    # Need to add new month section - insert after first ---
    awk -v month="$MONTH_HEADER" -v done="$(cat $TMP_DONE)" '
        /^---$/ && !inserted {
            print
            print ""
            print month
            print ""
            print "| ID | Title | Closed | Resolution |"
            print "|----|-------|--------|------------|"
            print done
            inserted=1
            next
        }
        { print }
    ' "$ARCHIVE" > "$TMP_INDEX"
    mv "$TMP_INDEX" "$ARCHIVE"
fi

# Remove done issues from INDEX.md Active Issues table
# Keep the Clocklane section intact but remove ✅ items
awk '
    /^## Clocklane Issues/ { in_clocklane=1 }
    /^## / && !/Clocklane/ { in_clocklane=0 }
    
    # Skip done items in Active Issues (not Clocklane)
    !in_clocklane && /^\| *(ARIA|AGY|INFRA)-[0-9]+/ && /\| *done *\|/i { next }
    
    # Skip done items in Clocklane section  
    in_clocklane && /^\| *CLOCK-[0-9]+/ && /✅ *(done|deployed)/i { next }
    
    { print }
' "$INDEX" > "$TMP_INDEX"
mv "$TMP_INDEX" "$INDEX"

# Update the summary counts
echo "📊 Updating summary counts..."

# Count remaining open issues
OPEN_COUNT=$(grep -cE '^\| *(ARIA|AGY|INFRA|CLOCK)-[0-9]+.*\| *open *\|' "$INDEX" || echo 0)
IN_PROGRESS=$(grep -cE '^\| *(ARIA|AGY|INFRA|CLOCK)-[0-9]+.*\| *in.?progress *\|' "$INDEX" || echo 0)
BLOCKED=$(grep -cE '^\| *(ARIA|AGY|INFRA|CLOCK)-[0-9]+.*\| *blocked *\|' "$INDEX" || echo 0)

# Update summary section (use awk to handle emoji safely)
awk -v open="$OPEN_COUNT" -v prog="$IN_PROGRESS" -v block="$BLOCKED" '
    /Open \|/ { gsub(/\| [0-9]+ \|$/, "| " open " |") }
    /In Progress \|/ { gsub(/\| [0-9]+ \|$/, "| " prog " |") }
    /Blocked \|/ { gsub(/\| [0-9]+ \|$/, "| " block " |") }
    /Done \(this week\)/ { gsub(/\| [0-9]+ \|$/, "| 0 |") }
    { print }
' "$INDEX" > "$TMP_INDEX" && mv "$TMP_INDEX" "$INDEX"

echo ""
echo "✅ Archived $ARCHIVED_COUNT issue(s) to ARCHIVE.md"
echo "   Updated INDEX.md summary counts"
