#!/usr/bin/env bash

#MISE description="Run checks before a commit (conditional on staged file types)"

set -e

source "$(git rev-parse --show-toplevel)/scripts/_helpers.sh"

ensure_working_directory!

# Convert space-separated STAGED list to newline-delimited for grep.
# $STAGED is exported by .git/hooks/pre-commit via git diff-index.
staged_lines() {
  echo "$STAGED" | tr ' ' '\n'
}

# Determine if we should gate checks on staged files.
# $STAGED is set by .git/hooks/pre-commit during git commit.
# When run directly (e.g., mise run dev:precommit), run all checks.
if [ -z "${STAGED:-}" ]; then
  debug_msg "No staged files in context — running all checks."
  SKIP_GATE=true
else
  SKIP_GATE=false
fi

# --- Shell scripts ---
if $SKIP_GATE || staged_lines | grep -qE '^scripts/|^\.shellcheckrc'; then
  debug_msg "Running shellcheck..."
  fd . 'scripts/' --exclude '*.hurl' -t file --exec shellcheck --color
fi

# --- Elixir ---
if $SKIP_GATE || staged_lines | grep -qE '^(lib/|test/|config/|mix\.exs|mix\.lock|priv/repo/migrations/|priv/gettext/|\.credo\.exs|\.formatter\.exs|\.sobelow-conf)'; then
  debug_msg "Running credo..."
  mix credo --strict

  debug_msg "Running sobelow..."
  mix sobelow --compact --exit

  debug_msg "Checking translations..."
  mix gettext.extract --check-up-to-date

  debug_msg "Checking formatting..."
  mix format --check-formatted

  debug_msg "Running tests..."
  mise run //:test
fi

# deps.unlock sub-gate: only when mix.exs or mix.lock changed
if $SKIP_GATE || staged_lines | grep -qE '^mix\.exs$|^mix\.lock$'; then
  debug_msg "Checking unused deps..."
  mix deps.unlock --unused
fi

# --- Assets (JS/TS/CSS) ---
if $SKIP_GATE || staged_lines | grep -qE '^assets/|^\.pi/extensions/.*\.(ts|js|json)$'; then
  debug_msg "Checking assets formatting..."
  prettier --check 'assets/css/**/*.css' 'assets/js/**/*.js' '.pi/extensions/**/*.{ts,js,json}' '!.pi/extensions/**/node_modules/**'
fi

# --- Documentation ---
if $SKIP_GATE || staged_lines | grep -qE '^docs/|^README\.md$'; then
  debug_msg "Checking docs formatting..."
  prettier --check 'docs/**/*.md' 'docs/**/*.livemd' 'README.md'
fi

# --- Backlog ---
if $SKIP_GATE || staged_lines | grep -qE '^backlog/'; then
  debug_msg "Checking backlog formatting..."
  prettier --check 'backlog/archive/**/*.md' 'backlog/completed/**/*.md' 'backlog/tasks/**/*.md' 'backlog/docs/**/*.md'
fi

# --- Presto ---
if $SKIP_GATE || staged_lines | grep -qE '^presto/'; then
  debug_msg "Checking presto..."
  (cd presto && mise run test)
fi

# --- Docker ---
if $SKIP_GATE || staged_lines | grep -qE '^Dockerfile$|^\.dockerignore$|^compose\.yaml$'; then
  debug_msg "Validating Docker image..."
  mise run dev:validate-docker-image
fi
