# --- Development Tools ---

.PHONY: install-git-hooks sync-prototypes install-melos clean-branches

install-melos:
	@if ! command -v melos >/dev/null 2>&1; then \
		echo "--> Melos not found. Installing globally via dart pub..."; \
		dart pub global activate melos; \
	else \
		echo "✅ Melos is already installed."; \
	fi

install-git-hooks:
	@echo "--> Installing Git hooks..."
	@ln -sf ../../scripts/git-hooks/pre-push .git/hooks/pre-push
	@echo "✅ pre-push hook installed successfully. Direct pushes to 'main' and 'dev' are now blocked."

sync-prototypes:
	@echo "--> Synchronizing prototypes from external repository..."
	@./scripts/sync-prototypes.sh

clean-branches:
	@echo "--> Cleaning up local branches (keeping protected branches)..."
	@CURRENT_BRANCH=$$(git branch --show-current); \
	if [ "$$CURRENT_BRANCH" != "main" ] && [ "$$CURRENT_BRANCH" != "dev" ]; then \
		echo "❌ Error: This command can only be run from 'main' or 'dev' branch."; \
		echo "   Current branch: $$CURRENT_BRANCH"; \
		echo "   Please checkout 'main' or 'dev' first."; \
		exit 1; \
	fi
	@if [ ! -f "PROTECTED_BRANCHES.md" ]; then \
		echo "⚠️  PROTECTED_BRANCHES.md not found. Aborting."; \
		exit 1; \
	fi
	@echo "\nProtected branches (will NOT be deleted):"
	@grep -E '^- `[^`]+`' PROTECTED_BRANCHES.md | sed 's/^- `\(.*\)`/  - \1/' 2>/dev/null || true
	@echo "\n⚠️  This will delete all other local branches."
	@read -p "Are you sure? (y/N): " confirm && [ "$$confirm" = "y" ] || [ "$$confirm" = "Y" ] || (echo "Aborted." && exit 1)
	@CURRENT_BRANCH=$$(git branch --show-current); \
	if [ "$$CURRENT_BRANCH" != "main" ] && [ "$$CURRENT_BRANCH" != "dev" ] && ! echo "$$CURRENT_BRANCH" | grep -q '^demo/'; then \
		echo "\n⚠️  You are on branch '$$CURRENT_BRANCH' which will be deleted."; \
		echo "Switching to 'dev' branch first..."; \
		git checkout dev || (echo "❌ Failed to checkout dev branch" && exit 1); \
	fi
	@echo "\nDeleting branches..."
	@DELETED=0; SKIPPED=0; \
	for branch in $$(git branch | sed 's/^[* ] //' | grep -v '^main$$' | grep -v '^dev$$' | grep -v '^demo/'); do \
		if grep -qE "^- \`$$branch\`" PROTECTED_BRANCHES.md 2>/dev/null; then \
			echo "  ⏭️  Skipping protected: $$branch"; \
			SKIPPED=$$((SKIPPED + 1)); \
		else \
			echo "  🗑️  Deleting: $$branch"; \
			git branch -D "$$branch" 2>/dev/null && DELETED=$$((DELETED + 1)) || echo "    ⚠️  Failed to delete $$branch"; \
		fi; \
	done; \
	echo "\n✅ Done! Deleted $$DELETED branch(es), skipped $$SKIPPED protected branch(es)."
