#!/bin/bash
# CI script to update coverage badge in README.md
# Usage: scripts/ci-update-coverage-badge.sh <coverage_percentage>

set -e

if [ -z "$1" ]; then
    echo "Error: Coverage percentage not provided"
    exit 1
fi

COVERAGE=$1

# Determine badge color
if (( $(echo "$COVERAGE >= 80" | bc -l) )); then
    COLOR="brightgreen"
elif (( $(echo "$COVERAGE >= 50" | bc -l) )); then
    COLOR="yellow"
else
    COLOR="red"
fi

BADGE_URL="https://img.shields.io/badge/coverage-${COVERAGE}%-${COLOR}?style=flat-square"

# Only update if coverage has actually changed
if grep -q "coverage-${COVERAGE}%" README.md; then
    echo "Coverage badge already up to date at ${COVERAGE}%"
    exit 0
fi

# Update README
sed -i "s|https://img.shields.io/badge/coverage-.*-.*?style=flat-square|${BADGE_URL}|" README.md

# Set up git
git config --global user.name "CI Bot"
git config --global user.email "ci@arcodange.fr"

# Set up credentials using Gitea token
if [ -n "$PACKAGES_TOKEN" ]; then
    git config --global credential.helper store
    echo "https://${PACKAGES_TOKEN}@gitea.arcodange.lab" > ~/.git-credentials
fi

git add README.md
if git commit -m "🤖 chore: update coverage badge to ${COVERAGE}% [skip ci]"; then
    # Try push with retry logic for race conditions
    for i in 1 2 3; do
        if git push; then
            echo "Successfully updated coverage badge to ${COVERAGE}%"
            # Update local repo to the new HEAD after successful push
            git fetch origin
            git reset --hard origin/${GITHUB_REF_NAME:-${CI_COMMIT_REF_NAME:-main}}
            exit 0
        else
            echo "Push attempt $i failed, retrying..."
            if [ $i -eq 3 ]; then
                echo "Final push attempt failed - another job may have updated the badge"
                git pull --rebase || true
                git push || echo "Recovery push also failed"
                # Ensure we're on the latest commit even if push failed
                git fetch origin
                git reset --hard origin/${GITHUB_REF_NAME:-${CI_COMMIT_REF_NAME:-main}}
            fi
            sleep 2
        fi
    done
else
    echo "No coverage change to commit"
fi