SESSION     = simplyllm
PORT       ?= 10000
LOG         = logs/server.log

.DEFAULT_GOAL := help

# ─────────────────────────────────────────────────────────────────────────────

.PHONY: up down restart logs attach status install test build publish help

up: ## Start API server in a background tmux session
	@mkdir -p logs
	@if tmux has-session -t $(SESSION) 2>/dev/null; then \
		echo "Already running. Use 'make restart' to restart, 'make attach' to view."; \
	else \
		tmux new-session -d -s $(SESSION) \
			"uv run python -m simplyllm --host 0.0.0.0 --port $(PORT) 2>&1 | tee $(LOG)"; \
		echo "Server started on :$(PORT)"; \
		echo "  log:    make logs"; \
		echo "  attach: make attach"; \
	fi

down: ## Stop API server
	@tmux kill-session -t $(SESSION) 2>/dev/null \
		&& echo "Server stopped." \
		|| echo "Server was not running."

restart: ## Restart API server
	@$(MAKE) --no-print-directory down
	@sleep 1
	@$(MAKE) --no-print-directory up

attach: ## Attach to server tmux session (Ctrl-B D to detach)
	tmux attach -t $(SESSION)

logs: ## Tail server log file
	@test -f $(LOG) || (echo "No log file yet. Start server with 'make up'."; exit 1)
	tail -f $(LOG)

status: ## Show server status + health endpoint
	@echo "── tmux sessions ──────────────────────────"
	@tmux has-session -t $(SESSION) 2>/dev/null \
		&& echo "  server : running  ($(SESSION))" \
		|| echo "  server : stopped"
	@echo "── health check ───────────────────────────"
	@curl -sf http://localhost:$(PORT)/health | python3 -m json.tool 2>/dev/null \
		|| echo "  (server not responding on :$(PORT))"

install: ## Install / update project in editable mode
	uv tool install --editable .

build: ## Build package for PyPI
	uv build

publish: build ## Build and publish to PyPI
	@uv publish --username __token__ --password pypi-AgEIcHlwaS5vcmcCJGNiNTg1MzYzLWNlYjItNDBkMS1iNTg0LWJkY2ViMDQyY2EyMgACKlszLCI4OWVjNTkyMy1hOWNhLTQ4NDQtYWExNi00MzBiZmNjNGYyMWYiXQAABiBB2FEW7XbJvOhW_z2KSezpZ_Vpitb--Au4jGSuvUjVug

test: ## Run benchmark (60 parallel requests via server, 1 min)
	PYTHONUNBUFFERED=1 uv run python -m simplyllm.test

test-direct: ## Run benchmark (direct provider calls, no server)
	PYTHONUNBUFFERED=1 uv run python -m simplyllm.test --direct

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