ROOT_DIR := $(shell pwd)
PYTHON ?= python3

.PHONY: help install uninstall sync-skill test

help:
	@echo "Usage: make [target]"
	@echo ""
	@echo "  install     Editable install + sync skill (PYTHON=$(PYTHON))"
	@echo "  sync-skill  Copy bundled agent skill to ~/.agents/skills/mytoolkit/"
	@echo "  test        Run the pytest suite"
	@echo "  uninstall   Uninstall mytoolkit and remove shell completions"

# Working tree: xiaohe-agent/packages/mytoolkit (submodule of apaam/mytoolkit).
# Refuse ephemeral GHA runner checkouts (_work) so PATH CLI cannot point there.
install:
	@case "$(ROOT_DIR)" in \
	  */_work/*|*/.xiaohe/actions-runner/*) \
	    echo "ERROR: refuse install from GHA runner worktree: $(ROOT_DIR)" >&2; \
	    echo "Use: cd <xiaohe-agent>/packages/mytoolkit && make install" >&2; \
	    exit 1 ;; \
	esac
	@echo "Installing editable mytoolkit"
	@echo "  ROOT=$(ROOT_DIR)"
	@echo "  PYTHON=$(PYTHON)"
	$(PYTHON) -m pip install -e "$(ROOT_DIR)" --upgrade
	@echo "Installing shell completions…"
	@mytoolkit completion install || echo "Warning: completion install failed"
	@$(MAKE) -s sync-skill
	@echo "Editable install:"
	@$(PYTHON) -m pip show mytoolkit | awk '/^(Name|Version|Location|Editable project location):/'
	@ed="$$($(PYTHON) -m pip show mytoolkit | awk -F': ' '/Editable project location:/ {print $$2}')"; \
	  case "$$ed" in \
	    */_work/*|*/.xiaohe/actions-runner/*) \
	      echo "ERROR: Editable still points at runner tree: $$ed" >&2; exit 1 ;; \
	  esac

sync-skill:
	@echo "Syncing agent skill to ~/.agents/skills/mytoolkit/ ..."
	@mkdir -p "$(HOME)/.agents/skills"
	@if command -v rsync >/dev/null 2>&1; then \
		rsync -av --delete "$(ROOT_DIR)/.agents/skills/mytoolkit/" "$(HOME)/.agents/skills/mytoolkit/"; \
	else \
		rm -rf "$(HOME)/.agents/skills/mytoolkit"; \
		cp -R "$(ROOT_DIR)/.agents/skills/mytoolkit" "$(HOME)/.agents/skills/mytoolkit"; \
	fi
	@# Cursor / Claude Code often resolve skills under ~/.claude/skills
	@if [[ -L "$(HOME)/.claude/skills/mytoolkit" ]]; then \
		echo " ~/.claude/skills/mytoolkit is symlink — skip copy"; \
	elif [[ -d "$(HOME)/.claude/skills" ]] || [[ -d "$(HOME)/.claude" ]]; then \
		echo "Mirroring skill to ~/.claude/skills/mytoolkit/ ..."; \
		mkdir -p "$(HOME)/.claude/skills"; \
		if command -v rsync >/dev/null 2>&1; then \
			rsync -av --delete "$(ROOT_DIR)/.agents/skills/mytoolkit/" "$(HOME)/.claude/skills/mytoolkit/"; \
		else \
			rm -rf "$(HOME)/.claude/skills/mytoolkit"; \
			cp -R "$(ROOT_DIR)/.agents/skills/mytoolkit" "$(HOME)/.claude/skills/mytoolkit"; \
		fi; \
	fi

uninstall:
	@mytoolkit uninstall || $(PYTHON) -m pip uninstall mytoolkit -y

test:
	@cd "$(ROOT_DIR)" && \
	if command -v uv >/dev/null 2>&1; then \
		uv run pytest tests/ -q; \
	else \
		$(PYTHON) -m pytest tests/ -q; \
	fi
