#!/usr/bin/env bash
#
# Pre-commit hook: Database Path Validation
#
# Validates database path consistency before allowing commits.
# This prevents regression to old 'dev_tokens.db' paths.
#
# Installation:
#   cp scripts/pre-commit.hook ../../.git/hooks/pre-commit
#   chmod +x ../../.git/hooks/pre-commit
#
# Or use: make install-hooks

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get the module directory (where this hook belongs)
MODULE_DIR="module/iron_token_manager"

# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
  echo -e "${RED}[✗] Not in a git repository${NC}"
  exit 1
fi

# Get repository root
REPO_ROOT=$(git rev-parse --show-toplevel)

# Check if the iron_token_manager module exists
if [ ! -d "$REPO_ROOT/$MODULE_DIR" ]; then
  # Not committing changes to iron_token_manager, skip validation
  exit 0
fi

echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}Pre-commit: Database Path Validation${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Check if we're committing changes to iron_token_manager
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep "^$MODULE_DIR/" || true)

if [ -z "$STAGED_FILES" ]; then
  echo -e "${GREEN}[✓]${NC} No iron_token_manager changes staged, skipping validation"
  exit 0
fi

echo -e "${BLUE}[INFO]${NC} iron_token_manager changes detected, running validators..."
echo ""

# Run path validator
VALIDATOR_SCRIPT="$REPO_ROOT/$MODULE_DIR/scripts/validate_db_paths.sh"

if [ ! -x "$VALIDATOR_SCRIPT" ]; then
  echo -e "${YELLOW}[⚠]${NC} Path validator not found or not executable: $VALIDATOR_SCRIPT"
  echo -e "${YELLOW}[⚠]${NC} Skipping validation (consider running: chmod +x $VALIDATOR_SCRIPT)"
  exit 0
fi

# Change to module directory and run validator
cd "$REPO_ROOT/$MODULE_DIR"

if ! ./scripts/validate_db_paths.sh; then
  echo ""
  echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${RED}[✗] COMMIT REJECTED${NC}"
  echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo -e "${YELLOW}Database path validation failed.${NC}"
  echo ""
  echo "Common fixes:"
  echo "  1. Replace 'dev_tokens.db' with './iron.db'"
  echo "  2. Use 'sqlite:///./iron.db?mode=rwc' in config files"
  echo "  3. Update backup naming to 'iron_backup_YYYYMMDD_HHMMSS.db'"
  echo ""
  echo "Run this command to see violations:"
  echo "  cd $MODULE_DIR && ./scripts/validate_db_paths.sh"
  echo ""
  exit 1
fi

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}[✓] All validations passed${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

exit 0
