.PHONY: build run dev stop logs test migrate clean install start restart status

APP_NAME := esp32-web
PORT := 5500
HOST := 0.0.0.0
PIDFILE := /tmp/esp32-web.pid
LOGFILE := /tmp/esp32-web.log

install:
	pip install -e ".[dev]"

# Server management
start:
	@if [ -f $(PIDFILE) ] && kill -0 $$(cat $(PIDFILE)) 2>/dev/null; then \
		echo "Server already running (PID $$(cat $(PIDFILE)))"; \
	else \
		echo "Starting server on $(HOST):$(PORT)..."; \
		nohup flask --app src/esp32_web run --host $(HOST) --port $(PORT) > $(LOGFILE) 2>&1 & \
		echo $$! > $(PIDFILE); \
		sleep 1; \
		echo "Server started (PID $$(cat $(PIDFILE)))"; \
	fi

stop:
	@if [ -f $(PIDFILE) ]; then \
		echo "Stopping server (PID $$(cat $(PIDFILE)))..."; \
		kill $$(cat $(PIDFILE)) 2>/dev/null || true; \
		rm -f $(PIDFILE); \
		echo "Server stopped"; \
	else \
		echo "Server not running"; \
	fi

restart: stop
	@sleep 1
	@$(MAKE) start

status:
	@if [ -f $(PIDFILE) ] && kill -0 $$(cat $(PIDFILE)) 2>/dev/null; then \
		echo "Server running (PID $$(cat $(PIDFILE)))"; \
		curl -s http://localhost:$(PORT)/health 2>/dev/null | \
			python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"Status: {d['status']}\nUptime: {d['uptime']}\")" 2>/dev/null \
			|| echo "Health: unreachable"; \
	else \
		echo "Server not running"; \
		rm -f $(PIDFILE) 2>/dev/null; \
	fi

logs:
	@tail -f $(LOGFILE)

dev:
	flask --app src/esp32_web run --host $(HOST) --port $(PORT) --debug

test:
	pytest -v

migrate:
	flask --app src/esp32_web db upgrade

migrate-init:
	flask --app src/esp32_web db init

migrate-create:
	flask --app src/esp32_web db migrate -m "$(msg)"

# Container targets
build:
	podman build -t $(APP_NAME) .

container-run:
	podman run -d --name $(APP_NAME) \
		-p $(PORT):$(PORT) \
		-p $(PORT):$(PORT)/udp \
		-v ./instance:/app/instance:Z \
		$(APP_NAME)

container-stop:
	podman stop $(APP_NAME) && podman rm $(APP_NAME)

container-logs:
	podman logs -f $(APP_NAME)

clean:
	rm -rf __pycache__ .pytest_cache .ruff_cache
	find . -type d -name __pycache__ -exec rm -rf {} +
	find . -type f -name "*.pyc" -delete
