#!/bin/bash
# =============================================================================
# PRE-COMMIT HOOK — generate-docs
# =============================================================================
# Distributed from pinky-workspace/core/hooks/ — do not edit in place. Universal (core/pre-commit/
# base.yaml): every repo gets it — README/index.md/badges are a cross-repo-type concern.
#
# 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,
#      so an edit to pyproject.toml's [project].description alone still refreshes them.
#   2. SVG quality badges (interrogate/coverage/noqa/hooks) — gated on staged src/ or
#      .pre-commit-config.yaml (more expensive: coverage xml + genbadge).
#
# The coverage badge runs the test suite itself every time rather than trusting a pre-existing
# .coverage file, 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 : ni garanti sur un shell macOS sans
# conda/venv activé, ni sur Windows. Le venv du projet passe en premier car le bloc coverage/pytest
# plus bas a besoin des deps de dev, qu'un python3 système n'a pas. `uv run` est écarté : il
# resynchronise l'env vers l'état par défaut et désinstalle les extras, résolvant un env de cache
# distinct de .venv. Un repo sans .venv retombe 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)

# Repo sans src/ : PKG_DIR est vide, et `git diff -- ""` sortirait en erreur pathspec vide.
# On court-circuite : pas de paquet, rien à jauger, SRC_STAGED reste à 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
        # genbadge est un console-script : le chercher dans le venv du projet avant le PATH —
        # un lookup PATH nu peut silencieusement résoudre le genbadge d'un tout autre repo.
        if [ -x .venv/bin/genbadge ]; then GB=".venv/bin/genbadge"                    # POSIX
        elif [ -x .venv/Scripts/genbadge.exe ]; then GB=".venv/Scripts/genbadge.exe"  # Windows
        elif command -v genbadge > /dev/null 2>&1; then GB="genbadge"
        else GB=""
        fi
        if [ -n "$GB" ]; then
            "$GB" 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 found (.venv nor PATH) — uv sync --group dev" >&2
        fi
    else
        # Le verdict pass/fail appartient au hook run-tests, qui bloque le commit en amont —
        # arriver ici veut dire que la suite casse sous instrumentation coverage spécifiquement,
        # ou que run-tests n'est pas actif sur ce repo. Ce hook fait des docs, pas de la garde
        # qualité : on reste non bloquant, mais on le dit.
        echo "⚠ coverage_badge.svg not regenerated: coverage 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
