.PHONY: help install install-deps detect-usb configure diagnose
.PHONY: firmware firmware-stop cli-shell
.PHONY: backend backend-stop
.PHONY: frontend frontend-build frontend-stop
.PHONY: stack-start stack-stop
.PHONY: docker-up docker-down docker-build docker-logs
.PHONY: web web-bg web-stop
.PHONY: test test-e2e test-integration test-all test-auto
.PHONY: clean format lint dev-install

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

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

# ── Installation ────────────────────────────────────────────
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

install-deps: ## Install all deps (firmware + backend + frontend)
	bash scripts/install-deps.sh

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

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

configure: $(VENV)/bin/activate detect-usb ## Auto-configure config.json
	@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"

diagnose: $(VENV)/bin/activate ## Run USB diagnostic tool
	@echo "Running USB diagnostics..."
	$(PYTHON) diagnose_usb.py

# ── Firmware (motor control + MQTT) ────────────────────────
firmware: $(VENV)/bin/activate ## Start firmware service (motor + MQTT)
	@echo "Starting firmware (MQTT motor controller)..."
	MQTT_BROKER_HOST=localhost MQTT_BROKER_PORT=1883 \
		$(PYTHON) -m firmware.main

firmware-stop: ## Stop firmware service
	@pkill -f 'firmware.main' 2>/dev/null && echo "Firmware stopped" || echo "Firmware not running"

cli-shell: $(VENV)/bin/activate ## Interactive CLI shell for motor control
	@echo "Starting CLI shell..."
	$(PYTHON) -m firmware.cli_shell

# ── Backend (FastAPI REST + WS) ────────────────────────────
backend: $(VENV)/bin/activate ## Start backend API server
	@echo "Starting backend on http://localhost:8000 ..."
	MQTT_BROKER_HOST=localhost MQTT_BROKER_PORT=1883 \
	BACKEND_HOST=0.0.0.0 BACKEND_PORT=8000 \
		$(PYTHON) -m backend.app

backend-stop: ## Stop backend server
	@pkill -f 'backend.app' 2>/dev/null && echo "Backend stopped" || echo "Backend not running"

# ── Frontend (React) ───────────────────────────────────────
frontend: ## Start frontend dev server
	@echo "Starting frontend on http://localhost:3000 ..."
	cd frontend && npm run dev

frontend-build: ## Build frontend for production
	cd frontend && npm run build

frontend-stop: ## Stop frontend dev server
	@pkill -f 'vite' 2>/dev/null && echo "Frontend stopped" || echo "Frontend not running"

# ── Full stack (no Docker) ─────────────────────────────────
stack-start: ## Start all services without Docker
	bash scripts/run-all.sh

stack-stop: ## Stop all services
	@pkill -f 'firmware.main' 2>/dev/null || true
	@pkill -f 'backend.app' 2>/dev/null || true
	@pkill -f 'vite' 2>/dev/null || true
	@pkill -f 'python web_panel.py' 2>/dev/null || true
	@echo "All services stopped"

# ── Docker ──────────────────────────────────────────────────
docker-build: ## Build Docker images
	docker compose -f docker-compose.fullstack.yml build

docker-up: ## Start full stack with Docker
	docker compose -f docker-compose.fullstack.yml up -d
	@echo ""
	@echo "Services running:"
	@echo "  Frontend:  http://localhost:3000"
	@echo "  Backend:   http://localhost:8000"
	@echo "  MQTT:      localhost:1883"

docker-down: ## Stop Docker stack
	docker compose -f docker-compose.fullstack.yml down

docker-logs: ## Show Docker logs
	docker compose -f docker-compose.fullstack.yml logs -f

# ── Legacy web panel ───────────────────────────────────────
web: $(VENV)/bin/activate ## Start legacy Flask web panel
	@echo "Starting legacy web panel on http://localhost:5000"
	$(PYTHON) web_panel.py

web-bg: $(VENV)/bin/activate ## Start legacy web panel in background
	$(PYTHON) web_panel.py &
	@echo $$! > web_panel.pid

web-stop: ## Stop legacy web panel
	@pkill -f 'python web_panel.py' 2>/dev/null && echo "Web panel stopped" || echo "Not running"
	@rm -f web_panel.pid

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

shell: ## Run legacy bash CLI shell
	bash cli_shell.sh

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

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

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

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

test-integration: ## Run integration tests
	$(PYTHON) tests/test_integration.py

test-all: test test-integration ## Run all tests

test-auto: ## Test auto-connect functionality
	$(PYTHON) test_auto_connect.py

# ── Dev tools ───────────────────────────────────────────────
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 firmware/*.py backend/*.py

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

clean: ## Clean build artifacts
	rm -rf $(VENV) build/ dist/ *.egg-info/
	rm -rf frontend/node_modules frontend/dist
	rm -rf backend/logs/logs.txt
	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"
