#!/bin/sh
# Always-on pre-commit validation gate for the workshop bundle.
#
# Git runs this script before it writes a commit; a non-zero exit blocks the
# commit. `setup-hook.cmd` / `setup-hook.sh` point this repository's
# core.hooksPath at the folder this file lives in, so the gate is on for every
# commit in the bundle from then on, in every exercise folder.
#
# What it does, on each commit:
#   1. reads the staged paths (`git diff --cached --name-only`);
#   2. finds every `*.SemanticModel` and `*.Report` folder those paths fall
#      under;
#   3. runs `te validate` on each staged semantic model and
#      `pbir validate --strict --semantic` on each staged report;
#   4. exits non-zero, blocking the commit, if any of them reports errors.
#
# A commit that stages no model and no report runs no validator and is not
# delayed.
#
# A validator that is not installed never blocks a commit. If a semantic model
# is staged and `te` is not on PATH, the gate prints one line saying the model
# was not validated, records the skip in its log, and lets the commit through;
# the same for `pbir` and a staged report. Only a validator that ran and
# reported errors blocks. A learner who has not installed the CLIs yet can
# still work; the log says which checks were off.
#
# `powerbi-report-author` (the Microsoft PBIR validator) is run for staged
# reports when it is installed, and its findings are printed, but it never
# blocks: on 2026-09-07 it reports 35 theme errors and exits 1 on the stock
# SpaceParts report in this bundle, so gating on it would block every report
# commit in every exercise. See docs/reference-validator-coverage.md.
#
# To turn the gate off:  git config core.hooksPath .git/hooks-disabled
set -u

repo=$(git rev-parse --show-toplevel) || exit 1
log="$repo/.git/precommit-gate.log"
stamp=$(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || echo unknown)

staged=$(git diff --cached --name-only)
if [ -z "$staged" ]; then
  echo "pre-commit: nothing staged; no validation to run."
  echo "$stamp PASSED nothing-staged" >>"$log" 2>/dev/null
  exit 0
fi

# Longest-prefix walk: print the ancestor folder of each staged path whose
# name ends in the given suffix. One line per distinct folder.
roots_with_suffix() {
  suffix=$1
  printf '%s\n' "$staged" | awk -v sfx="$suffix" -F/ '
    {
      p = ""
      for (i = 1; i <= NF; i++) {
        p = (p == "" ? $i : p "/" $i)
        if (length($i) >= length(sfx) &&
            substr($i, length($i) - length(sfx) + 1) == sfx) { print p; break }
      }
    }' | sort -u
}

models=$(roots_with_suffix ".SemanticModel")
reports=$(roots_with_suffix ".Report")

if [ -z "$models" ] && [ -z "$reports" ]; then
  echo "pre-commit: no semantic model and no report staged; nothing to validate."
  echo "$stamp PASSED no-model-or-report-staged" >>"$log" 2>/dev/null
  exit 0
fi

failed=0
ran=0

have_te=0
if command -v te >/dev/null 2>&1; then
  have_te=1
elif [ -n "$models" ]; then
  echo "pre-commit: te is not installed, so the semantic model was not validated. Install it from the setup section to turn this check on."
fi

have_pbir=0
if command -v pbir >/dev/null 2>&1; then
  have_pbir=1
elif [ -n "$reports" ]; then
  echo "pre-commit: pbir is not installed, so the report was not validated. Install it from the setup section to turn this check on."
fi

for model in $models; do
  [ -d "$repo/$model" ] || continue
  if [ "$have_te" -eq 0 ]; then
    echo "$stamp SKIPPED te $model" >>"$log" 2>/dev/null
    continue
  fi
  ran=1
  echo "pre-commit: te validate $model --errors-only"
  if te validate "$repo/$model" --errors-only --non-interactive; then
    echo "$stamp PASSED te $model" >>"$log" 2>/dev/null
  else
    failed=1
    echo "$stamp BLOCKED te $model" >>"$log" 2>/dev/null
  fi
done

for report in $reports; do
  [ -d "$repo/$report" ] || continue
  if [ "$have_pbir" -eq 1 ]; then
    ran=1
    echo "pre-commit: pbir validate $report --strict --semantic"
    if pbir validate "$repo/$report" --strict --semantic; then
      echo "$stamp PASSED pbir $report" >>"$log" 2>/dev/null
    else
      failed=1
      echo "$stamp BLOCKED pbir $report" >>"$log" 2>/dev/null
    fi
  else
    echo "$stamp SKIPPED pbir $report" >>"$log" 2>/dev/null
  fi
  pbip="$repo/${report%.Report}.pbip"
  if command -v powerbi-report-author >/dev/null 2>&1 && [ -f "$pbip" ]; then
    # Summary line only. Its full output is dominated by theme findings that
    # every stock SpaceParts report in this bundle already has, which would
    # bury whatever the commit actually broke.
    summary=$(powerbi-report-author validate "$pbip" --format text 2>&1 \
      | grep -E 'result=' | tail -1)
    echo "pre-commit: Microsoft validator (informational, never blocks): ${summary:-no summary}"
    echo "pre-commit: for detail: powerbi-report-author validate \"$pbip\" --format text"
  fi
done

if [ "$failed" -eq 0 ]; then
  if [ "$ran" -eq 0 ]; then
    echo "pre-commit: no validator was available to run; allowing the commit."
  else
    echo "pre-commit: the validators reported no errors; allowing the commit."
  fi
  exit 0
fi

echo "pre-commit: BLOCKED - a validator reported errors above." >&2
echo "pre-commit: repair what it named and commit again." >&2
echo "pre-commit: do not pass --no-verify; that skips this gate instead of" >&2
echo "pre-commit: fixing what it found." >&2
exit 1
