#!/usr/bin/env bash

set -euo pipefail

###############################################################################
# Root README generator for ConcourseGPT
# Generates an overview README that summarizes all documented pipelines
###############################################################################

# Source required utilities
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
source "${SCRIPT_DIR}/utils/formatting.sh"
source "${SCRIPT_DIR}/utils/llm.sh"
source "${SCRIPT_DIR}/utils/helpers.sh"

# Generate root README
# No args - works with docs/ directory
generate_root_readme() {
    print_progress "Finding pipelines" "..."
    
    # Find all pipeline directories
    local pipeline_dirs=()
    while IFS= read -r dirpath; do
        pipeline_dirs+=("$(basename "$dirpath")")
    done < <(find docs -mindepth 1 -maxdepth 1 -type d | sort)

    if [ ${#pipeline_dirs[@]} -eq 0 ]; then
        print_progress "Finding pipelines" "skip"
        echo "No pipeline directories found under docs/. Skipping README generation."
        return 0
    fi

    print_progress "Finding pipelines" "success"
    printf "      Found: %s\n" "${pipeline_dirs[*]}"

    print_progress "Generating README" "..."

    # Read prompt template from file
    local prompt_template
    prompt_template=$(<"${ROOT_DIR}/prompts/root-readme.md")
    
    # Handle the variable part (pipeline directories) using a temp file
    local temp_prompt
    temp_prompt=$(mktemp)
    printf '%s\n' "${pipeline_dirs[@]}" > "$temp_prompt"
    pipeline_list=$(cat "$temp_prompt")
    rm "$temp_prompt"
    
    # Replace placeholder with actual pipeline directories
    local prompt="${prompt_template/\$(printf '%s\\n' \"\${pipeline_dirs[@]}\")/$pipeline_list}"

    local response
    if ! response=$(call_llm_api_with_validation "$prompt"); then
        print_progress "Generating README" "error"
        return 1
    fi

    local out_file="docs/README.md"
    {
        echo "$response"
        echo
        echo "<!-- Generated by ConcourseGPT -->"
    } > "$out_file"

    print_progress "Generating README" "success"
    echo "      Output: $out_file"
}

# If this script is run directly, show usage
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo "This script is meant to be sourced and used as part of ConcourseGPT"
    exit 1
fi
