#!/usr/bin/env bash

# Enable strict mode
set -euo pipefail

# gh-md-toc download URL
GH_MD_TOC_URL="https://raw.githubusercontent.com/ekalinin/github-markdown-toc/c386c7b41956158867d7b8b5c6620a2ce6fbe939/gh-md-toc"

# Check for --ensure-gh-md-toc flag
ENSURE_GH_MD_TOC=false
if [ "${1:-}" = "--ensure-gh-md-toc" ]; then
    ENSURE_GH_MD_TOC=true
    shift
fi

# Auto-detect or install gh-md-toc
GH_MD_TOC=""

# First, check if gh-md-toc is in PATH
if command -v gh-md-toc &> /dev/null; then
    GH_MD_TOC="gh-md-toc"
# If not in PATH, check current directory
elif [ -x "./gh-md-toc" ]; then
    GH_MD_TOC="./gh-md-toc"
# If not in current directory, check ~/.local/bin/
elif [ -x "$HOME/.local/bin/gh-md-toc" ]; then
    GH_MD_TOC="$HOME/.local/bin/gh-md-toc"
# If not found anywhere, prompt for installation or auto-install
else
    if [ "$ENSURE_GH_MD_TOC" = true ]; then
        echo "gh-md-toc not found. Installing to current directory..."
        INSTALL_GH_MD_TOC=true
    else
        echo "gh-md-toc is required but not found."
        echo "This script can automatically download and install it to the current directory."
        echo "Source: $GH_MD_TOC_URL"
        echo ""
        read -p "Would you like to install gh-md-toc now? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            INSTALL_GH_MD_TOC=true
        else
            echo "Installation cancelled. Please install gh-md-toc manually or run with --ensure-gh-md-toc flag."
            echo "Manual installation (to current directory):"
            echo "  curl -o gh-md-toc $GH_MD_TOC_URL"
            echo "  chmod +x gh-md-toc"
            exit 1
        fi
    fi

    if [ "$INSTALL_GH_MD_TOC" = true ]; then
        # Download gh-md-toc to current directory
        echo "Downloading gh-md-toc..."
        if curl -o gh-md-toc "$GH_MD_TOC_URL"; then
            # Make it executable
            chmod +x gh-md-toc

            GH_MD_TOC="./gh-md-toc"

            echo "gh-md-toc installed successfully!"
        else
            echo "Error: Failed to download gh-md-toc. Please check your internet connection."
            exit 1
        fi
    fi
fi

python docs/tmpl_readme.py
"$GH_MD_TOC" --insert --no-backup --hide-footer README.md
