#!/bin/bash

# Script to generate release notes with changelog from commits between tags
# Usage: ./gen-release-notes [output_file]
# If output_file is not provided, outputs to stdout

set -e

OUTPUT_FILE="${1:-}"

# Get the latest release tag (this will be the previous tag for the new release)
PREVIOUS_TAG=$(gh release list --limit 1 --json tagName -q '.[0].tagName' 2>/dev/null || echo "")

if [ -z "$PREVIOUS_TAG" ]; then
    echo "Warning: Could not find release tags from GitHub, trying git tags" >&2
    # Try to get the latest tag from git
    PREVIOUS_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
    
    if [ -z "$PREVIOUS_TAG" ]; then
        echo "Error: Could not find any release tags" >&2
        exit 1
    fi
fi

# Get current version from build.zig.zon for the release title
CURRENT_VERSION=$(grep -E '^\s*\.version\s*=' build.zig.zon | sed -E 's/.*"([^"]+)".*/\1/' || echo "HEAD")

echo "Generating changelog from $PREVIOUS_TAG to HEAD (v${CURRENT_VERSION})..." >&2

# Read the base RELEASE.md
BASE_CONTENT=$(cat .github/RELEASE.md)

# Get repository owner and name for commit URLs
REPO_OWNER="nurulhudaapon"
REPO_NAME="zx"
REPO_URL="https://github.com/${REPO_OWNER}/${REPO_NAME}"

# Get commits between previous tag and HEAD with SHA and message
# Use temporary files to avoid subshell issues with arrays
TMP_COMMITS="/tmp/changelog_commits.txt"
rm -f "$TMP_COMMITS"

# Try GitHub API first
gh api "repos/${REPO_OWNER}/${REPO_NAME}/compare/${PREVIOUS_TAG}...HEAD" --jq '.commits[] | "\(.sha)|\(.commit.message | split("\n")[0])"' > "$TMP_COMMITS" 2>/dev/null || true

# If GitHub API failed or returned empty, use git log
if [ ! -s "$TMP_COMMITS" ]; then
    echo "Warning: GitHub API failed, using git log" >&2
    git log "${PREVIOUS_TAG}..HEAD" --pretty=format:"%H|%s" > "$TMP_COMMITS" 2>/dev/null || true
fi

# Categorize commits with links
FEATURES=()
DOCS=()
FIXES=()
OTHER=()

# Process commits from file
while IFS='|' read -r sha message || [ -n "$sha" ]; do
    if [[ -z "$sha" ]] || [[ -z "$message" ]]; then
        continue
    fi
    
    # Create commit link (short SHA)
    SHORT_SHA="${sha:0:7}"
    COMMIT_LINK="[\`${SHORT_SHA}\`](${REPO_URL}/commit/${sha})"
    COMMIT_ENTRY="${message} ${COMMIT_LINK}"
    
    if [[ "$message" =~ ^feat ]]; then
        FEATURES+=("$COMMIT_ENTRY")
    elif [[ "$message" =~ ^docs ]]; then
        DOCS+=("$COMMIT_ENTRY")
    elif [[ "$message" =~ ^fix ]]; then
        FIXES+=("$COMMIT_ENTRY")
    else
        OTHER+=("$COMMIT_ENTRY")
    fi
done < "$TMP_COMMITS"

rm -f "$TMP_COMMITS"

# Generate changelog section
{
    echo "## Changelog"
    echo ""
    echo "### v${CURRENT_VERSION}"
    echo ""
    
    if [ ${#FEATURES[@]} -gt 0 ]; then
        echo "#### Features"
        for feat in "${FEATURES[@]}"; do
            echo "- ${feat}"
        done
        echo ""
    fi
    

    
    if [ ${#FIXES[@]} -gt 0 ]; then
        echo "#### Fixes"
        for fix in "${FIXES[@]}"; do
            echo "- ${fix}"
        done
        echo ""
    fi

    if [ ${#DOCS[@]} -gt 0 ]; then
        echo "#### Documentation"
        for doc in "${DOCS[@]}"; do
            echo "- ${doc}"
        done
        echo ""
    fi
    
    if [ ${#OTHER[@]} -gt 0 ]; then
        echo "#### Miscellaneous"
        for other in "${OTHER[@]}"; do
            echo "- ${other}"
        done
        echo ""
    fi    
} > /tmp/changelog.txt

# Combine base content with changelog
if [ -n "$OUTPUT_FILE" ]; then
    {
        echo "$BASE_CONTENT"
        echo ""
        cat /tmp/changelog.txt
    } > "$OUTPUT_FILE"
    echo "Release notes generated: $OUTPUT_FILE" >&2
else
    echo "$BASE_CONTENT"
    echo ""
    cat /tmp/changelog.txt
fi
rm -f /tmp/changelog.txt

