#!/usr/bin/env bash
# git pre-commit hook. runs Biome, rustfmt, clippy, and GitHub Actions workflow checks before every commit
set -euo pipefail

# skip in CI. github actions already runs biome check independently
if [ -n "${CI:-}" ]; then
  exit 0
fi

exit_code=0

echo "🔍 Running formatting checks (lint-staged)…"
if ! pnpm exec lint-staged; then
  echo ""
  echo "❌ Formatting failed. See errors above."
  exit_code=1
fi

# rustfmt + clippy (Rust)

# only run clippy if there are staged Rust files
rust_staged=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.rs$' || true)

if [ -n "$rust_staged" ]; then
  echo "🔍 Running clippy…"

  # matches CI exactly: --all-targets -D warnings
  if cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings; then
    echo "✅ Clippy passed."
  else
    echo ""
    echo "❌ Clippy found issues."
    echo "   Fix the errors above, then re-stage and try again."
    exit_code=1
  fi
fi

# GitHub Actions workflow checks
workflow_staged=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^\.github/workflows/.*\.yml$' || true)

if [ -n "$workflow_staged" ]; then
  echo "🔍 Checking GitHub Actions workflows…"

  if command -v actionlint >/dev/null 2>&1 && command -v yq >/dev/null 2>&1; then
    if actionlint .github/workflows/*.yml; then
      echo "✅ actionlint passed."
    else
      echo ""
      echo "❌ actionlint found issues."
      exit_code=1
    fi

    if yq '.' .github/workflows/*.yml >/dev/null; then
      echo "✅ Workflow YAML is valid."
    else
      echo ""
      echo "❌ Workflow YAML parsing failed."
      exit_code=1
    fi
  else
    echo "⚠️  actionlint or yq not found in PATH. Skipping workflow checks."
    echo "   Run with nix develop to enable them."
  fi
fi

# Nix hashes check
lockfiles_staged=$(git diff --cached --name-only | grep -E '^(pnpm-lock\.yaml|src-tauri/Cargo\.lock)$' || true)
nix_source_staged=$(git diff --cached --name-only | grep -E '^nix/packages/source\.nix$' || true)

if [ -n "$lockfiles_staged" ] && [ -z "$nix_source_staged" ]; then
  echo ""
  echo "⚠️ Lockfiles staged without updated Nix hashes. Running update-hashes.sh..."
  if ./scripts/update-hashes.sh; then
    git add nix/packages/source.nix
    echo "✅ Hashes updated and staged automatically."
  else
    echo "❌ Failed to update hashes. Quitting."
    exit_code=1
  fi
fi

exit $exit_code
