.PHONY: install web web-stop cli test clean help detect-usb configure status home

VENV = .venv
PYTHON = $(VENV)/bin/python
PIP = $(VENV)/bin/pip
FLASK_PORT = 5000

help: ## Show this help message
	@echo "Available targets:"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-15s\033[0m %s\n", $$1, $$2}'

install: ## Full installation (system deps, udev rules, venv, python deps)
	@echo "🔧 Running full installation..."
	@bash -c 'if [ \$$EUID -ne 0 ]; then echo "⚠️  Running without sudo. For udev rules, run: sudo make install"; fi'
	bash setup.sh

detect-usb: $(VENV)/bin/activate ## Detect USB device and show configuration
	@echo "🔍 Detecting Pololu USB device..."
	$(PYTHON) detect_usb.py

configure: $(VENV)/bin/activate detect-usb ## Auto-configure config.json with detected device
	@echo "📝 Auto-configuring settings..."
	$(PYTHON) detect_usb.py | grep -A20 "Suggested config" | tail -n +2 > /tmp/usb_config.json 2>/dev/null || true
	@echo "✓ Run 'make detect-usb' to see device config, then update config.json"

$(VENV)/bin/activate: requirements.txt pyproject.toml
	python3 -m venv $(VENV)
	$(PIP) install --upgrade pip
	$(PIP) install -e .

test: $(VENV)/bin/activate ## Run tests
	$(PYTHON) -m pytest tests/ -v

web: $(VENV)/bin/activate ## Start web control panel
	@echo "🌐 Starting web panel on http://localhost:$(FLASK_PORT)"
	$(PYTHON) web_panel.py

web-bg: $(VENV)/bin/activate ## Start web panel in background
	@echo "🌐 Starting web panel in background on http://localhost:$(FLASK_PORT)"
	$(PYTHON) web_panel.py &
	@echo $$! > web_panel.pid
	@echo "✓ Web panel started (PID: $$(cat web_panel.pid))"

web-stop: ## Stop background web panel
	@if [ -f web_panel.pid ]; then \
		kill $$(cat web_panel.pid) 2>/dev/null && echo "✓ Web panel stopped" || echo "✓ Web panel not running"; \
		rm -f web_panel.pid; \
	else \
		echo "No PID file found, web panel may not be running"; \
	fi

cli: $(VENV)/bin/activate ## Run CLI controller
	$(PYTHON) tic_t249_controller.py $(ARGS)

shell: ## Run interactive CLI shell
	@echo "🐚 Starting CLI shell..."
	bash cli_shell.sh

status: $(VENV)/bin/activate ## Check motor status
	$(PYTHON) tic_t249_controller.py status

home: $(VENV)/bin/activate ## Perform homing (reverse direction)
	$(PYTHON) tic_t249_controller.py home-reverse

clean: ## Clean build artifacts and virtual environment
	rm -rf $(VENV)
	rm -rf build/
	rm -rf dist/
	rm -rf *.egg-info/
	rm -f web_panel.pid
	find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
	find . -type f -name "*.pyc" -delete 2>/dev/null || true
	@echo "✓ Cleaned"

# Development targets
dev-install: $(VENV)/bin/activate ## Install with dev dependencies
	$(PIP) install -e ".[dev]"

format: $(VENV)/bin/activate ## Format code with black
	$(PYTHON) -m black *.py

lint: $(VENV)/bin/activate ## Lint code with ruff
	$(PYTHON) -m ruff check *.py
