#!/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.
#
# BLOCKING exception to the non-blocking posture above: when uv is available the suite runs
# via `uv run --frozen --all-extras` so every optional extra's tests execute; without uv on
# the machine the fallback interpreter runs the suite and the skip-guard alone protects the
# badge. If the suite STILL reports a skip whose reason is a missing import, the badge is
# refused and the hook exits 1 — a coverage figure measured in a stripped env is wrong data,
# and must not be written.
# =============================================================================

# 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é POUR CE
# BLOC (render_docs.py est 100 % stdlib) — le run de couverture, lui, passe précisément par
# `uv run --frozen --all-extras` (voir plus bas) pour que l'env porte chaque extra. Un repo sans .venv
# retombe sur python3/py.
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)
    # La suite passe par `uv run --frozen --all-extras` : l'env resynchronisé porte alors chaque
    # extra — sans lui, un env amputé fait skippier les tests des modules concernés et le badge
    # mesure une couverture effondrée (~59 % au lieu de ~84 %). Sans uv sur la machine, repli sur
    # le python du venv tel quel : le garde-fou ci-dessous refuse alors la mesure d'un env dégradé.
    if command -v uv > /dev/null 2>&1; then
        # --frozen : un commit ne re-lock jamais uv.lock — l'env resync sur le lock présent.
        COV_RUN="uv run --frozen --all-extras coverage run"
        # Le xml passe par uv aussi : PY est résolu AVANT que uv ne crée/sync le .venv — le
        # python système n'a pas coverage, et son échec avalisé ferait échouer genbadge en silence.
        COV_XML="uv run --frozen --all-extras coverage xml"
        REMEDY="uv sync --all-extras"
    else
        COV_RUN="$PY -m coverage run"
        COV_XML="$PY -m coverage xml"
        REMEDY="resync the project .venv with every extra installed"
    fi
    # -rs : rapporte la RAISON de chaque skip — c'est l'entrée du garde-fou suivant.
    if $COV_RUN -m pytest -q -rs --no-cov > "$COV_LOG" 2>&1; then
        # Garde-fou env dégradé : un skip dont la raison est un import absent (« not installed »,
        # « No module named », « could not import ») signale un extra manquant, quelle que soit
        # la façon dont l'env a été amputé. Refus d'écrire le badge, skip fautif nommé, exit 1.
        # || true : grep rc=1 (aucun match) reste « aucun skip », pas un échec, si un set -e arrive.
        IMPORT_SKIPS=$(grep -Ei "SKIPPED .*(not installed|No module named|could not import)" "$COV_LOG" || true)
        if [ -n "$IMPORT_SKIPS" ]; then
            echo "✖ coverage_badge.svg not written: skipped tests with a missing import (degraded env — $REMEDY):" >&2
            printf '%s\n' "$IMPORT_SKIPS" >&2
            exit 1
        fi
        $COV_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
