#!/usr/bin/env bash
#
# Regenerate the theme's .min.css / .min.js assets and stage them alongside the
# sources they were built from, so a commit can never contain an edited asset
# without its minified sibling.
#
# Install with `pixi run install-hooks` (sets core.hooksPath to .githooks).
# Bypass with `git commit --no-verify` — the wheel build re-minifies from source
# anyway, so a bypass costs you a stale file in git, not a bad release.
set -euo pipefail

REPO="$(git rev-parse --show-toplevel)"
THEME="$REPO/atlasdocs-theme"
[ -d "$THEME" ] || THEME="$REPO"

# Only run when an asset the generator reads is part of this commit.
if ! git diff --cached --name-only --diff-filter=ACMR \
  | grep -qE 'atlasdocs_theme/theme/assets/(stylesheets|javascripts)/[^/]+\.(css|js)$'; then
  exit 0
fi

cd "$THEME"

if command -v pixi >/dev/null 2>&1; then
  pixi run --frozen minify
else
  python3 scripts/minify_assets.py
fi

# Stage whatever the run changed. `git add` on an unchanged file is a no-op, so
# this neither creates empty diffs nor pulls in unrelated work.
git add \
  atlasdocs_theme/theme/assets/stylesheets/*.min.css \
  atlasdocs_theme/theme/assets/javascripts/*.min.js
