#!/bin/bash
# Check Codex CLI session files per day
# Usage: Run this on the developer's machine
# Codex stores sessions at: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl

SESSIONS_DIR="$HOME/.codex/sessions"

if [ ! -d "$SESSIONS_DIR" ]; then
    echo "ERROR: $SESSIONS_DIR does not exist"
    echo "Codex CLI has never been used on this machine, or sessions are stored elsewhere."
    exit 1
fi

echo "=== Codex CLI Session Files Report ==="
echo "Directory: $SESSIONS_DIR"
echo ""

total_files=0
total_size=0

echo "Date              | Files | Total Size"
echo "------------------|-------|----------"

# Find all date directories and list files per day
for year_dir in "$SESSIONS_DIR"/*/; do
    [ -d "$year_dir" ] || continue
    for month_dir in "$year_dir"*/; do
        [ -d "$month_dir" ] || continue
        for day_dir in "$month_dir"*/; do
            [ -d "$day_dir" ] || continue

            # Extract date from path
            year=$(basename "$(dirname "$(dirname "$day_dir")")")
            month=$(basename "$(dirname "$day_dir")")
            day=$(basename "$day_dir")
            date_str="$year-$month-$day"

            # Count files and size
            file_count=$(find "$day_dir" -name "rollout-*.jsonl" -type f 2>/dev/null | wc -l)
            if [ "$file_count" -gt 0 ]; then
                day_size=$(find "$day_dir" -name "rollout-*.jsonl" -type f -exec du -cb {} + 2>/dev/null | tail -1 | cut -f1)
                day_size_kb=$((day_size / 1024))
                total_files=$((total_files + file_count))
                total_size=$((total_size + day_size))
                printf "%-17s | %5d | %d KB\n" "$date_str" "$file_count" "$day_size_kb"
            fi
        done
    done
done

echo "------------------|-------|----------"
printf "%-17s | %5d | %d KB\n" "TOTAL" "$total_files" "$((total_size / 1024))"
echo ""

# Show most recent 5 files
echo "=== 5 Most Recent Session Files ==="
find "$SESSIONS_DIR" -name "rollout-*.jsonl" -type f -printf '%T@ %p\n' 2>/dev/null | sort -rn | head -5 | while read -r ts file; do
    mod_date=$(date -d "@${ts%.*}" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || date -r "${ts%.*}" '+%Y-%m-%d %H:%M:%S' 2>/dev/null)
    size=$(du -h "$file" | cut -f1)
    echo "  $mod_date  $size  $(basename "$file")"
done
