#!/bin/bash
# =============================================================================
# PRE-COMMIT HOOK — generate-docs (renamed/extended from check-docs-up-to-date, 2026-07-10)
# =============================================================================
# Distributed from pinky-workspace/core/hooks/ — do not edit in place. Universal (core/pre-commit/
# base.yaml): every repo gets it, not just the snowflake extra — README/index.md/badges are a
# cross-repo-type concern, not a Snowflake one.
#
# Two independent jobs:
#   1. Repo-local README.md + docs/index.md regeneration (badges/tagline/documentation/license) —
#      via render_docs.py, ALWAYS run (cheap + idempotent), never gated on which files are staged.
#      That unconditional run is the fix for the bug that motivated this hook: editing
#      pyproject.toml's [project].description used to leave README/index stale until the next
#      manual `setup.py --all` — gating on staged src/ files missed exactly that edit.
#   2. SVG quality badges (interrogate/coverage/noqa/hooks) — unchanged from check-docs-up-to-date,
#      still gated on staged src/ or .pre-commit-config.yaml (more expensive: coverage xml + genbadge).
# =============================================================================

# 1. Repo-local docs (README sections + docs/index.md) — always, idempotent.
python scripts/hooks/render_docs.py
git add README.md 2>/dev/null
git add docs/index.md 2>/dev/null

# 2. SVG quality badges — only when their inputs are staged (detect the package dir under src/).
PKG_DIR=$(find src -maxdepth 1 -mindepth 1 -type d -not -name '__pycache__' 2>/dev/null | head -1)

SRC_STAGED=$(git diff --cached --name-only -- "$PKG_DIR" | grep -v '__pycache__' | wc -l | tr -d ' ')
CONFIG_STAGED=$(git diff --cached --name-only -- .pre-commit-config.yaml | wc -l | tr -d ' ')

if [ "$CONFIG_STAGED" -gt 0 ]; then
    python scripts/hooks/generate_ci_badges.py --hooks > /dev/null 2>&1
    git add docs/reference/generated/hooks_badge.svg 2>/dev/null
fi

if [ "$SRC_STAGED" -gt 0 ]; then
    git add docs/reference/generated/interrogate_badge.svg 2>/dev/null

    if [ -f ".cache/coverage/.coverage" ] && command -v genbadge > /dev/null 2>&1; then
        coverage xml --data-file=.cache/coverage/.coverage -o .cache/coverage/coverage.xml > /dev/null 2>&1
        genbadge coverage -i .cache/coverage/coverage.xml -o docs/reference/generated/coverage_badge.svg > /dev/null 2>&1
        git add docs/reference/generated/coverage_badge.svg 2>/dev/null
    fi

    python scripts/hooks/generate_ci_badges.py --noqa > /dev/null 2>&1
    git add docs/reference/generated/noqa_badge.svg 2>/dev/null
fi

exit 0
