.PHONY: install web web-stop cli test clean help

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: ## Install dependencies and setup environment
	@echo "🔧 Installing..."
	bash setup.sh

$(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)

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
