# ---------------------------------------------------------------------------
# Vibex — Local Development Makefile
#
# All services run natively. No containers needed (uses SQLite).
# Shared Traefik routes vibex.msrashed.com → localhost:8100
#
# PIDs → /tmp/vibex/pids/<service>.pid
# Logs → /tmp/vibex/logs/<service>.log
# ---------------------------------------------------------------------------

.PHONY: help start stop restart status logs \
	start-bot stop-bot restart-bot logs-bot \
	start-web stop-web restart-web logs-web dev \
	start-mcp stop-mcp restart-mcp logs-mcp \
	build install build-frontend rebuild dist publish \
	lint format typecheck test check clean clean-db

# ── Config ────────────────────────────────────────────────────────────────────

PID_DIR      := /tmp/vibex/pids
LOG_DIR      := /tmp/vibex/logs
FRONTEND_DIR := web/frontend
WEB_PORT     ?= 8100

# ── Helpers ───────────────────────────────────────────────────────────────────

define svc_start
	@mkdir -p $(PID_DIR) $(LOG_DIR)
	@if [ -f $(PID_DIR)/$(1).pid ] && kill -0 $$(cat $(PID_DIR)/$(1).pid) 2>/dev/null; then \
		echo "  $(1)  already running  (PID $$(cat $(PID_DIR)/$(1).pid))"; \
	else \
		$(2) > $(LOG_DIR)/$(1).log 2>&1 & echo $$! > $(PID_DIR)/$(1).pid; \
		sleep $(or $(3),2); \
		if kill -0 $$(cat $(PID_DIR)/$(1).pid) 2>/dev/null; then \
			echo "  $(1)  started  pid=$$(cat $(PID_DIR)/$(1).pid)  log=$(LOG_DIR)/$(1).log"; \
		else \
			echo "  $(1)  failed to start — check $(LOG_DIR)/$(1).log"; \
			rm -f $(PID_DIR)/$(1).pid; \
		fi; \
	fi
endef

define svc_stop
	@if [ -f $(PID_DIR)/$(1).pid ]; then \
		PID=$$(cat $(PID_DIR)/$(1).pid); \
		kill $$PID 2>/dev/null; pkill -P $$PID 2>/dev/null; \
		rm -f $(PID_DIR)/$(1).pid; \
		echo "  $(1)  stopped  (was PID $$PID)"; \
	else \
		echo "  $(1)  not running"; \
	fi
endef

# ── All services ──────────────────────────────────────────────────────────────

start: start-bot start-mcp ## Start all services (bot embeds web when WEB_API_ENABLED=true)

stop: stop-web stop-mcp stop-bot ## Stop all services

restart: stop start ## Restart all services

status: ## Show status of all services
	@printf "%-10s %-8s %s\n" "SERVICE" "PID" "STATUS"
	@printf "%-10s %-8s %s\n" "-------" "---" "------"
	@for svc in bot web mcp; do \
		if [ -f $(PID_DIR)/$$svc.pid ]; then \
			PID=$$(cat $(PID_DIR)/$$svc.pid); \
			if kill -0 $$PID 2>/dev/null; then \
				printf "%-10s %-8s \033[32mrunning\033[0m\n" "$$svc" "$$PID"; \
			else \
				printf "%-10s %-8s \033[31mdead (stale pid)\033[0m\n" "$$svc" "$$PID"; \
			fi; \
		elif [ "$$svc" = "web" ] && lsof -i :$(WEB_PORT) -sTCP:LISTEN >/dev/null 2>&1; then \
			printf "%-10s %-8s \033[32mrunning (embedded)\033[0m\n" "$$svc" "-"; \
		else \
			printf "%-10s %-8s \033[33mstopped\033[0m\n" "$$svc" "-"; \
		fi; \
	done

logs: ## Tail all service logs
	@tail -f $(LOG_DIR)/bot.log $(LOG_DIR)/web.log $(LOG_DIR)/mcp.log

# ── Telegram Bot ──────────────────────────────────────────────────────────────

start-bot: ## Start Telegram bot
	$(call svc_start,bot,nohup uv run vibex)

stop-bot: ## Stop Telegram bot
	$(call svc_stop,bot)

restart-bot: stop-bot start-bot ## Restart Telegram bot

logs-bot: ## Tail bot logs
	@tail -f $(LOG_DIR)/bot.log

# ── Web Server (port 8100) ────────────────────────────────────────────────────

, := ,
start-web: ## Start web server on port 8100
	$(call svc_start,web,WEB_API_ENABLED=true MCP_HTTP_ENABLED=true nohup uv run python -c "import uvicorn; from vibex.web.app import create_app; uvicorn.run(create_app()$(,) host='0.0.0.0'$(,) port=$(WEB_PORT)$(,) log_level='info')",3)

stop-web: ## Stop web server (standalone only; embedded web stops with bot)
	@if [ -f $(PID_DIR)/web.pid ]; then \
		PID=$$(cat $(PID_DIR)/web.pid); \
		kill $$PID 2>/dev/null; pkill -P $$PID 2>/dev/null; \
		rm -f $(PID_DIR)/web.pid; \
		echo "  web  stopped  (was PID $$PID)"; \
	else \
		echo "  web  not running (standalone)"; \
	fi

restart-web: stop-web start-web ## Restart web server

logs-web: ## Tail web logs
	@tail -f $(LOG_DIR)/web.log

dev: ## Run web server with hot reload (foreground)
	WEB_API_ENABLED=true MCP_HTTP_ENABLED=true \
	uv run uvicorn vibex.web.app:create_app --factory \
		--host 0.0.0.0 --port $(WEB_PORT) --reload \
		--reload-dir src/vibex/web

# ── MCP Server (port 7891) ────────────────────────────────────────────────────

start-mcp: ## Start MCP HTTP server on port 7891
	$(call svc_start,mcp,nohup uv run vibex-mcp-sse)

stop-mcp: ## Stop MCP server
	$(call svc_stop,mcp)

restart-mcp: stop-mcp start-mcp ## Restart MCP server

logs-mcp: ## Tail MCP logs
	@tail -f $(LOG_DIR)/mcp.log

# ── Build ─────────────────────────────────────────────────────────────────────

build: install build-frontend ## Install deps + build frontend

install: ## Install Python dependencies
	uv sync --extra web --extra stt --extra dev

build-frontend: ## Build Next.js static export
	cd $(FRONTEND_DIR) && npm ci && rm -rf .next out && \
		NEXT_PUBLIC_API_TOKEN=$$(grep -s 'MCP_TOKEN=' ~/.vibex/.env | cut -d= -f2) \
		npm run build

rebuild: build-frontend stop-web start-web ## Build frontend + restart web

# ── Distribution ──────────────────────────────────────────────────────────────

dist: build-frontend ## Build wheel + sdist (requires frontend)
	uv build

publish: dist ## Build and publish to PyPI
	uv publish

# ── Quality ───────────────────────────────────────────────────────────────────

lint: ## Run ruff linter
	uv run ruff check src/ tests/

format: ## Auto-format with ruff
	uv run ruff format src/ tests/

typecheck: ## Run pyright type checker
	uv run pyright src/vibex/

test: ## Run pytest
	uv run pytest

check: lint typecheck test ## Run all checks

# ── Cleanup ───────────────────────────────────────────────────────────────────

clean: ## Remove build artifacts
	rm -rf $(FRONTEND_DIR)/.next $(FRONTEND_DIR)/out dist/
	find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true

clean-db: ## Delete all databases (fresh start)
	rm -f ~/.vibex/vibex.db ~/.vibex/web.db
	@echo "Databases removed — will be recreated on next start"

# ── Help ──────────────────────────────────────────────────────────────────────

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

.DEFAULT_GOAL := help
