#!/bin/bash

# ====================================================================================
# SCRIPT TO SETUP STANDARD GITHUB LABELS FROM A YAML FILE (v4 - Robust Bash Parsing)
# ====================================================================================
set -e # Exit script if a command fails

LABELS_FILE="labels.yml"

echo "🚀 Setting up GitHub labels from '${LABELS_FILE}'..."

# --- Function to create or edit a label ---
create_or_edit_label() {
    NAME=$1
    DESCRIPTION=$2
    COLOR=$3
    
    if [ -z "$NAME" ] || [ -z "$DESCRIPTION" ] || [ -z "$COLOR" ]; then
        echo "⚠️  Skipping invalid label entry."
        return
    fi

    # The `gh api` command will exit with a non-zero status if the label is not found (404).
    # We redirect stderr to /dev/null to silence the expected "Not Found" error message.
    if gh api "repos/{owner}/{repo}/labels/${NAME}" --silent 2>/dev/null; then
        echo "  - Editing existing label: '${NAME}'"
        gh label edit "${NAME}" --description "${DESCRIPTION}" --color "${COLOR}"
    else
        echo "  - Creating new label: '${NAME}'"
        gh label create "${NAME}" --description "${DESCRIPTION}" --color "${COLOR}"
    fi
}

# --- Read and Parse YAML File using a robust while loop ---
# This approach is more reliable than complex sed/awk pipelines.
name=""
description=""
color=""

while IFS= read -r line || [[ -n "$line" ]]; do
    # Skip comments and empty lines
    if [[ "$line" =~ ^\s*# ]] || [[ -z "$line" ]]; then
        continue
    fi

    # Check for name
    if [[ "$line" =~ -[[:space:]]+name:[[:space:]]+\"(.*)\" ]]; then
        # If we find a new name, and the previous one was complete, process it.
        if [ -n "$name" ] && [ -n "$description" ] && [ -n "$color" ]; then
            create_or_edit_label "$name" "$description" "$color"
            # Reset for the next entry
            description=""
            color=""
        fi
        name="${BASH_REMATCH[1]}"
    # Check for description
    elif [[ "$line" =~ [[:space:]]+description:[[:space:]]+\"(.*)\" ]]; then
        description="${BASH_REMATCH[1]}"
    # Check for color
    elif [[ "$line" =~ [[:space:]]+color:[[:space:]]+\"(.*)\" ]]; then
        color="${BASH_REMATCH[1]}"
    fi
done < "$LABELS_FILE"

# Process the very last label in the file
if [ -n "$name" ] && [ -n "$description" ] && [ -n "$color" ]; then
    create_or_edit_label "$name" "$description" "$color"
fi


echo ""
echo "🎉 All standard labels have been created or updated successfully."