#!/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).
#
# Coverage badge reliability fix (2026-07-12): the old version trusted a pre-existing
# .cache/coverage/.coverage file — silently stale for a month on pinky-core (nobody's commit
# happened to run a full, correctly-instrumented `pytest` right before hitting this hook) with
# no failure, no warning, nothing. It now runs the test suite itself, every time, and prints a
# visible warning instead of silently no-op'ing when pytest or genbadge aren't available. Uses
# `coverage run -m pytest --no-cov` (not pytest-cov's own instrumentation) — editable-install
# path setups (multiple repos' src/ on sys.path at once) can make pytest-cov silently measure
# nothing ("module-not-measured") with no visible error; wrapping externally sidesteps that.
# =============================================================================

# 0. Interpréteur — résolu explicitement, jamais `python` nu (2026-07-22). `python` n'existe ni dans
# un shell macOS sans conda ni venv activé (homebrew ne pose que `python3`), ni sur une machine
# Windows vanilla ; il ne marchait ici que par l'auto-activation de conda base, porteuse par accident.
# Le venv du projet passe en premier parce que le bloc coverage/pytest plus bas a besoin des deps de
# dev — un `python3` système ne les a pas, donc un simple `python` → `python3` casserait ce bloc au
# lieu de le réparer. `uv run` est écarté : il resynchronise l'env vers l'état par défaut et
# désinstalle les extras, puis résout un env de cache distinct de .venv (mesuré, voir la card
# uv-run-strips-extras-trap). Les repos sans .venv (studio, assets, infra, workspace) retombent sur
# python3/py, suffisant pour render_docs.py qui est 100 % stdlib.
if [ -x .venv/bin/python ]; then PY=".venv/bin/python"                    # POSIX
elif [ -x .venv/Scripts/python.exe ]; then PY=".venv/Scripts/python.exe"  # Windows
elif command -v python3 > /dev/null 2>&1; then PY="python3"
elif command -v py > /dev/null 2>&1; then PY="py -3"
else
    echo "⚠ generate-docs: aucun interpréteur Python (.venv / python3 / py) — docs non régénérées" >&2
    exit 0
fi

# 1. Repo-local docs (README sections + docs/index.md) — always, idempotent.
$PY 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)

# Repos sans src/ (workspace, studio, assets, infra) : PKG_DIR est vide, et `git diff -- ""` sort en
# `fatal: empty string is not a valid pathspec`. Bénin (le hook sort 0 quand même) mais il crachait ce
# fatal à chaque commit sur ces 4 repos. Pas de paquet → rien à jauger, SRC_STAGED vaut 0.
if [ -n "$PKG_DIR" ]; then
    SRC_STAGED=$(git diff --cached --name-only -- "$PKG_DIR" | grep -v '__pycache__' | wc -l | tr -d ' ')
else
    SRC_STAGED=0
fi
CONFIG_STAGED=$(git diff --cached --name-only -- .pre-commit-config.yaml | wc -l | tr -d ' ')

if [ "$CONFIG_STAGED" -gt 0 ]; then
    $PY 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

    mkdir -p .cache/coverage
    COV_LOG=$(mktemp)
    if $PY -m coverage run -m pytest -q --no-cov > "$COV_LOG" 2>&1; then
        $PY -m coverage xml -o .cache/coverage/coverage.xml > /dev/null 2>&1
        if command -v genbadge > /dev/null 2>&1; then
            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
        else
            echo "⚠ coverage_badge.svg not regenerated: 'genbadge' not installed — pip install -e '.[dev]'" >&2
        fi
    else
        echo "⚠ coverage_badge.svg not regenerated: test run failed, see $COV_LOG" >&2
    fi

    $PY 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
