#!/bin/sh

# 定义颜色
YELLOW='\033[1;33m'
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

# 自动更新逻辑
HOOK_SOURCE=".dart_tool/flutter_pre_commit/pre-commit"
HOOK_TARGET=".git/hooks/pre-commit"
if [ -f "$HOOK_SOURCE" ] && ! cmp -s "$HOOK_SOURCE" "$HOOK_TARGET"; then
  echo "🔄 ${YELLOW}Updating Flutter pre-commit hook...${NC}"
  cp -f "$HOOK_SOURCE" "$HOOK_TARGET"
  chmod +x "$HOOK_TARGET"
  exec "$HOOK_TARGET"
fi

changed_files=$(git diff --cached --name-only --diff-filter=ACM "*.dart")
[ -z "$changed_files" ] && exit 0

# 1. 检查 Flutter Lint
echo "🔍 ${YELLOW}Running Flutter lint check...${NC}"
lint_output=$(flutter analyze $changed_files 2>&1)
lint_exit_code=$?

if [ $lint_exit_code -ne 0 ]; then
  echo "$lint_output"
  echo "\n${RED}❌ Flutter lint check failed! Fix issues before commit.${NC}"
  exit 1
fi

# 2. 检查并自动修复 Dart 格式
echo "📝 ${YELLOW}Checking Dart format...${NC}"
format_failed=false
if ! dart format --output=none --set-exit-if-changed $changed_files; then
  format_failed=true
fi

if [ "$format_failed" = true ]; then
  echo "⚠️ ${YELLOW}Format issues found, auto-fixing...${NC}"
  dart format $changed_files >/dev/null

  if dart format --output=none --set-exit-if-changed $changed_files; then
    echo "${GREEN}✅ Format fixed, staging changes...${NC}"
    git add $changed_files
  else
    echo "${RED}❌ Auto-fix failed! Run 'dart format .' manually.${NC}"
    exit 1
  fi

  echo "${GREEN}✅ Fix complete! Re-run 'git commit' to proceed.${NC}"
  exit 1
fi

echo "${GREEN}✅ All checks passed!${NC}"
exit 0