#!/bin/bash

# Script to find all commits that changed dqn.py, starting from most recent
# Usage:
#   ./find_dqn_commit.sh                    # Show all commits with diffs
#   ./find_dqn_commit.sh 10                 # Show last 10 commits with diffs
#   ./find_dqn_commit.sh --summary          # Show all commits without diffs
#   ./find_dqn_commit.sh 10 --summary       # Show last 10 commits without diffs

# Path to dqn.py file
DQN_FILE="agilerl/algorithms/dqn.py"

# Parse arguments
LIMIT=""
SUMMARY=false

for arg in "$@"; do
    if [ "$arg" = "--summary" ] || [ "$arg" = "-s" ]; then
        SUMMARY=true
    elif echo "$arg" | grep -qE '^[0-9]+$'; then
        LIMIT="$arg"
    fi
done

# Check if file exists
if [ ! -f "$DQN_FILE" ]; then
    echo "Error: File $DQN_FILE not found"
    exit 1
fi

# Build git log command
GIT_LOG_CMD="git log --format=%H -- $DQN_FILE"
if [ -n "$LIMIT" ]; then
    GIT_LOG_CMD="$GIT_LOG_CMD -n $LIMIT"
fi

# Get commit hashes that modified this file
COMMITS=$($GIT_LOG_CMD)

if [ -z "$COMMITS" ]; then
    echo "Error: No commit history found for $DQN_FILE"
    exit 1
fi

# Count total commits (before limit)
TOTAL_ALL=$(git log --format="%H" -- "$DQN_FILE" | wc -l | tr -d ' ')
TOTAL_SHOWN=$(echo "$COMMITS" | wc -l | tr -d ' ')

if [ -n "$LIMIT" ]; then
    echo "Showing last $LIMIT commit(s) out of $TOTAL_ALL total commits that changed $DQN_FILE"
else
    echo "Found $TOTAL_ALL commit(s) that changed $DQN_FILE"
fi
echo "=========================================="
echo ""

# Iterate through each commit
COMMIT_NUM=1
while IFS= read -r COMMIT_HASH; do
    echo "=========================================="
    if [ -n "$LIMIT" ]; then
        echo "Commit #$COMMIT_NUM of $TOTAL_SHOWN (out of $TOTAL_ALL total)"
    else
        echo "Commit #$COMMIT_NUM of $TOTAL_ALL"
    fi
    echo "=========================================="
    echo "Commit hash: $COMMIT_HASH"
    echo ""
    echo "Commit details:"
    git log -1 --format="%an <%ae>%n%ad%n%s%n%b" "$COMMIT_HASH" -- "$DQN_FILE"
    echo ""
    
    if [ "$SUMMARY" = false ]; then
        echo "Diff:"
        git show "$COMMIT_HASH" -- "$DQN_FILE"
    fi
    
    echo ""
    echo ""
    
    COMMIT_NUM=$((COMMIT_NUM + 1))
done <<< "$COMMITS"
