# 实验一 Makefile：修复坏 Skill（写代码→检查→验证 闭环）
# 常用：make setup → make doctor → make check

VENV ?= .venv
PY   := $(VENV)/bin/python

.PHONY: help setup doctor lint test check clean

help:  ## 显示本帮助
	@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN{FS=":.*?## "}{printf "  \033[36m%-12s\033[0m %s\n", $$1, $$2}'

setup:  ## 创建 venv 并安装依赖（ruff / pytest）
	python3 -m venv $(VENV)
	$(VENV)/bin/pip install -q --upgrade pip
	$(VENV)/bin/pip install -q -r requirements.txt
	@echo "✓ 依赖安装完成，运行 make doctor 验证环境"

doctor:  ## 环境自检：python3 / venv / ruff / pytest / 实验材料
	@command -v python3 >/dev/null 2>&1 || { echo "✗ 未找到 python3，请先安装 Python 3.9+"; exit 1; }
	@echo "✓ python3: $$(python3 --version 2>&1)"
	@test -x $(PY) || { echo "✗ 未找到 $(VENV)，先运行 make setup"; exit 1; }
	@test -x $(VENV)/bin/ruff || { echo "✗ ruff 未安装，先运行 make setup"; exit 1; }
	@echo "✓ ruff:  $$($(VENV)/bin/ruff --version 2>&1)"
	@$(PY) -c "import pytest" 2>/dev/null || { echo "✗ pytest 未安装，先运行 make setup"; exit 1; }
	@echo "✓ pytest: $$($(PY) -m pytest --version 2>&1)"
	@test -f exercise/led_controller.py || { echo "✗ 缺少练习代码（exercise/）"; exit 1; }
	@test -f exercise/tests/test_led_controller.py || { echo "✗ 缺少测试文件（exercise/tests/）"; exit 1; }
	@test -f skills/firmware-vibe-workflow/SKILL.md || { echo "✗ 缺少待修复的 skill（skills/）"; exit 1; }
	@echo "✓ 实验材料齐全"
	@echo "doctor 完成：运行 make check 查看练习初始状态（预期 lint 报 2 处、测试 3 个失败）"

lint:  ## ruff 静态检查（初始状态：应恰好报 2 处）
	@test -x $(VENV)/bin/ruff || { echo "✗ 先运行 make setup"; exit 1; }
	$(VENV)/bin/ruff check exercise/

test:  ## pytest 运行测试（初始状态：应恰好 3 failed, 8 passed）
	@test -x $(PY) || { echo "✗ 先运行 make setup"; exit 1; }
	$(PY) -m pytest exercise/tests/ -v

check:  ## 一键验收：lint + test（实验目标：全绿；初始状态应失败并展示全部问题）
	@test -x $(PY) || { echo "✗ 先运行 make setup"; exit 1; }
	@status=0; \
	$(MAKE) lint || status=1; \
	echo ""; \
	$(MAKE) test || status=1; \
	echo ""; \
	if [ $$status -ne 0 ]; then \
		echo "✗ make check 未通过：详见上方 lint / test 输出"; \
		exit 1; \
	fi; \
	echo "✓ make check 全绿：lint 0 问题 + 全部测试通过"

clean:  ## 清理 venv 与缓存
	rm -rf $(VENV)
	find . -type d -name __pycache__ -prune -exec rm -rf {} +
	find . -type d -name .pytest_cache -prune -exec rm -rf {} +
	find . -type d -name .ruff_cache -prune -exec rm -rf {} +
	@echo "✓ 已清理"
