#!/bin/bash
# SPDX-FileCopyrightText: Red Hat
#
# SPDX-License-Identifier: Apache-2.0

# Generate a markdown test inventory from Ginkgo e2e test outlines.
# Uses `ginkgo outline --format json` to parse test structure without
# executing tests, then transforms the JSON into readable markdown.
#
# Usage: hack/generate-e2e-outline.sh [output-file]
# Default output: docs/dev/e2e-test-overview.md

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
E2E_DIR="${REPO_ROOT}/test/e2e"
OUTPUT="${1:-${REPO_ROOT}/docs/dev/e2e-test-overview.md}"

# Ensure ginkgo is available
GINKGO="go run github.com/onsi/ginkgo/v2/ginkgo"

# Process a single JSON outline file into markdown
process_outline() {
    local file="$1"
    local relpath="${file#"${REPO_ROOT}/"}"

    ${GINKGO} outline --format json "${file}" | jq -r --arg file "${relpath}" '
        # Recursive function to process nodes
        def process_nodes(depth):
            .[] |
            if .name == "Describe" or .name == "Context" or .name == "When" then
                # Container node — emit as heading or bold section
                if depth == 0 then
                    # Top-level Describe
                    "\n## " + .text +
                    (if (.labels // []) | length > 0 then
                        " [" + ((.labels // []) | join(", ")) + "]"
                    else "" end) +
                    "\n\nFile: `" + $file + "`\n"
                elif depth == 1 then
                    "\n### " + .text +
                    (if (.labels // []) | length > 0 then
                        " [" + ((.labels // []) | join(", ")) + "]"
                    else "" end) + "\n"
                else
                    "\n**" + .text + "**\n"
                end,
                # Process children
                (if .nodes then (.nodes | process_nodes(depth + 1)) else empty end)
            elif .name == "It" or .name == "Specify" then
                # Spec node — emit as numbered list item
                "1. " + .text +
                (if (.labels // []) | length > 0 then
                    " [" + ((.labels // []) | join(", ")) + "]"
                else "" end),
                # Process By steps as indented bullets
                (if .nodes then
                    (.nodes[] | select(.name == "By") |
                        "   - " + .text)
                else empty end)
            elif .name == "By" and depth <= 1 then
                # Top-level By (in BeforeAll/AfterAll) — emit as setup step
                "- " + .text
            else empty end;

        # Start processing
        process_nodes(0)
    '
}

# Generate the document
{
    cat <<'HEADER'
<!--
SPDX-FileCopyrightText: Red Hat

SPDX-License-Identifier: Apache-2.0
-->

<!-- This file is auto-generated by hack/generate-e2e-outline.sh -->
<!-- To regenerate: make e2e-outline -->

# E2E Test Overview

This document provides an overview of all end-to-end test cases.
It is generated from the test source code using Ginkgo's outline
feature, which parses test structure without executing tests.

HEADER

    # Process each test file (excluding suite setup)
    for file in "${E2E_DIR}"/*_test.go; do
        basename="$(basename "${file}")"
        if [[ "${basename}" == "e2e_suite_test.go" ]]; then
            continue
        fi
        process_outline "${file}"
    done

} | awk '
    # Post-process: ensure blank lines between different list types and
    # remove consecutive blank lines (markdownlint MD032 and MD012)
    {
        # Insert blank line when transitioning from bullet list to numbered list
        if (/^1\. / && prev ~ /^- /) print ""
        # Suppress consecutive blank lines
        if (/^$/ && prev ~ /^$/) next
        print
        prev = $0
    }
' > "${OUTPUT}.tmp"

# Insert a TOC after the intro paragraph by extracting ## and ### headings
{
    # Print everything up to and including the blank line after the intro
    sed -n '1,/^feature, which parses/p' "${OUTPUT}.tmp"
    echo ""

    # Build TOC from headings
    echo "## Contents"
    echo ""
    grep -E '^##+ ' "${OUTPUT}.tmp" | grep -v '^# ' | grep -v '^## Contents' | while IFS= read -r line; do
        # Strip leading ## or ### and build anchor
        text="${line#\#\#\# }"
        indent=""
        if [[ "${line}" == "### "* ]]; then
            indent="  "
        else
            text="${line#\#\# }"
        fi
        # Build GitHub-style anchor: lowercase, spaces→dashes, strip non-alnum except dash
        anchor=$(echo "${text}" | tr '[:upper:]' '[:lower:]' | \
            sed 's/ /-/g; s/[^a-z0-9_-]//g; s/--*/-/g')
        echo "${indent}- [${text}](#${anchor})"
    done

    # Print everything after the intro paragraph
    sed -n '/^feature, which parses/,${/^feature, which parses/d;p}' "${OUTPUT}.tmp"
} > "${OUTPUT}"
rm -f "${OUTPUT}.tmp"

echo "Generated: ${OUTPUT}"
