#!/bin/bash
# Helper script to update changelog and footer links
#
# Usage:
#   ./bin/build/update-changelog.sh 2.23.0       # Prepare release 2.23.0 (before tagging)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

cd "$PROJECT_ROOT"

# Get the version argument if provided
NEW_VERSION="$1"

echo "🔄 Updating changelog..."

# Get the latest tag
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")

if [ -n "$NEW_VERSION" ]; then
    # Releasing a specific version - generate for unreleased commits
    echo "📝 Preparing release ${NEW_VERSION}"

    # Generate unreleased changelog
    pnpm exec git-cliff --unreleased --tag $NEW_VERSION --prepend CHANGELOG.md

    # Replace [Unreleased] with the version and today's date
    TODAY=$(date +%Y-%m-%d)
    CLEAN_VERSION=$(echo "$NEW_VERSION" | sed 's/^v//')
    VERSION_ANCHOR=$(echo "$CLEAN_VERSION" | sed 's/\./_/g')

    # Replace the Unreleased section header with the version header
    sed -i "s/## \[Unreleased\]\[unreleased\]/<a id=\"${VERSION_ANCHOR}\"><\/a>\n\n## [${CLEAN_VERSION}] - ${TODAY}/" CHANGELOG.md

    # Remove trailing whitespace
    sed -i 's/[[:space:]]*$//' CHANGELOG.md

    echo "✅ Added version section for ${CLEAN_VERSION}"

    # Update LATEST_TAG to the new version for footer processing
    LATEST_TAG="v${CLEAN_VERSION}"
else
    # No version specified - just update unreleased
    echo "📝 Updating unreleased commits"
    pnpm exec git-cliff --unreleased --prepend CHANGELOG.md
fi

# Update footer links
if [ -n "$NEW_VERSION" ]; then
    # We're preparing a release - update footer for the new version
    CLEAN_VERSION=$(echo "$NEW_VERSION" | sed 's/^v//')
    PREV_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")

    if [ -n "$PREV_TAG" ]; then
        # Replace or add the version link
        if grep -q "^\[${CLEAN_VERSION}\]:" CHANGELOG.md; then
            sed -i "s|^\[${CLEAN_VERSION}\]:.*|[${CLEAN_VERSION}]: https://github.com/deltachat/deltachat-desktop/compare/${PREV_TAG}...v${CLEAN_VERSION}|" CHANGELOG.md
        else
            # Add new version link at the top of the footer
            if grep -q "^\[unreleased\]:" CHANGELOG.md; then
                sed -i "/^\[unreleased\]:/a [${CLEAN_VERSION}]: https://github.com/deltachat/deltachat-desktop/compare/${PREV_TAG}...v${CLEAN_VERSION}" CHANGELOG.md
            else
                # No links yet, add before the generated comment
                if grep -q "<!-- generated by git-cliff -->" CHANGELOG.md; then
                    sed -i "/<!-- generated by git-cliff -->/i [${CLEAN_VERSION}]: https://github.com/deltachat/deltachat-desktop/compare/${PREV_TAG}...v${CLEAN_VERSION}\n" CHANGELOG.md
                fi
            fi
        fi

        # Update unreleased link to point from new version
        if grep -q "^\[unreleased\]:" CHANGELOG.md; then
            sed -i "s|^\[unreleased\]:.*|[unreleased]: https://github.com/deltachat/deltachat-desktop/compare/v${CLEAN_VERSION}...HEAD|" CHANGELOG.md
        else
            # Add unreleased link
            if grep -q "^\[${CLEAN_VERSION}\]:" CHANGELOG.md; then
                sed -i "/^\[${CLEAN_VERSION}\]:/i [unreleased]: https://github.com/deltachat/deltachat-desktop/compare/v${CLEAN_VERSION}...HEAD" CHANGELOG.md
            fi
        fi
        echo "✅ Updated footer links for ${CLEAN_VERSION}"
    fi
elif [ -n "$LATEST_TAG" ]; then
    # No new version - just update unreleased link
    if grep -q "^\[unreleased\]:" CHANGELOG.md; then
        sed -i "s|^\[unreleased\]:.*|[unreleased]: https://github.com/deltachat/deltachat-desktop/compare/${LATEST_TAG}...HEAD|" CHANGELOG.md
        echo "✅ Updated [unreleased] link"
    fi
fi

echo "✅ Changelog updated!"
