.PHONY: build up stop down clean logs logs-service test loadtest loadtest-stress restart help dev dev-office

# Docker Compose with project name and env-file for variable substitution
COMPOSE = docker compose --env-file=.local.env -p hands-system

# Number of replicas for the Office API
OFFICE_API_REPLICAS = 2

# Build all Docker images
build:
	@echo "Building all Docker images..."
	$(COMPOSE) build

# Start entire stack in Docker (build + run + migrate + seed)
up:
	@echo "Starting HANDS SYSTEM..."
	$(COMPOSE) up -d --build --scale office-api=$(OFFICE_API_REPLICAS)
	@echo "Waiting for services to be healthy..."
	@sleep 10
	@echo ""
	@echo "=========================================="
	@echo "Services Status:"
	@echo "=========================================="
	@$(COMPOSE) ps
	@echo ""
	@echo "=========================================="
	@echo "HANDS SYSTEM is ready!"
	@echo "=========================================="
	@echo "Vue.js Admin Dashboard: http://localhost"
	@echo "Office API via Traefik: http://localhost/api"
	@echo "Auth via Traefik:       http://localhost/auth"
	@echo "AI Chat Backend:        http://localhost/chat"
	@echo "Streamlit Frontend:     http://localhost/streamlit"
	@echo "Traefik Dashboard:      http://localhost:8888"
	@echo "MySQL (direct):         localhost:3306"
	@echo "=========================================="

# Stop all containers (preserve volumes/data)
stop:
	@echo "Stopping all containers..."
	$(COMPOSE) stop

# Stop and remove containers (preserve volumes)
down:
	@echo "Stopping and removing containers..."
	$(COMPOSE) down

# Stop and remove containers AND volumes (full reset)
clean:
	@echo "Removing all containers, networks, and volumes..."
	$(COMPOSE) down -v
	@echo "All containers and volumes removed."

# Show logs for key services
logs:
	$(COMPOSE) logs -f traefik office-api vue-frontend backend-chat frontend-chat db-migrate

# Show logs for specific service
logs-service:
	@if [ -z "$(SERVICE)" ]; then \
		echo "Usage: make logs-service SERVICE=<service-name>"; \
		echo "Available services: office-api, traefik, vue-frontend, backend-chat, frontend-chat, mysql-db, db-migrate"; \
	else \
		$(COMPOSE) logs -f $(SERVICE); \
	fi

# Run tests (placeholder — add pytest when tests are written)
test:
	@echo "Running tests..."
	$(COMPOSE) run --rm office-api python -m pytest backend/office/tests/ -v || echo "No tests found yet"

# Run k6 load test (ramp: 5→10→20→0 VUs, ~90 s)
# Requires: system running (make up). k6 runs in Docker — no local install needed.
loadtest:
	@echo "============================================"
	@echo "  HANDS SYSTEM — Load Test"
	@echo "  Stages: 5 VUs→10 VUs→20 VUs (ramp-up/peak/cool-down)"
	@echo "============================================"
	@echo "Obtaining JWT token..."
	@TOKEN=$$(curl -s -X POST http://localhost/auth/login \
		-H 'Content-Type: application/json' \
		-d '{"email":"admin@hwt.ch","password":"admin123"}' \
		| python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null); \
	if [ -z "$$TOKEN" ]; then \
		echo "ERROR: Could not obtain JWT token."; \
		echo "Check credentials or run: make up"; \
		exit 1; \
	fi; \
	echo "Token obtained. Launching k6 inside hands-system network..."; \
	mkdir -p load_tests/results; \
	docker run --rm \
		--network hands-system \
		-v "$(PWD)/load_tests:/scripts" \
		-e JWT_TOKEN=$$TOKEN \
		-e BASE_URL=http://traefik \
		grafana/k6:latest run /scripts/k6_script.js; \
	echo "Results saved to load_tests/results/summary.json"

# Stress test — ramp to 50 VUs to find the breaking point
loadtest-stress:
	@echo "============================================"
	@echo "  HANDS SYSTEM — Stress Test (up to 50 VUs)"
	@echo "============================================"
	@echo "Obtaining JWT token..."
	@TOKEN=$$(curl -s -X POST http://localhost/auth/login \
		-H 'Content-Type: application/json' \
		-d '{"email":"aar@company.ch","password":"Admin123!"}' \
		| python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null); \
	if [ -z "$$TOKEN" ]; then \
		echo "ERROR: Could not obtain JWT token."; \
		exit 1; \
	fi; \
	mkdir -p load_tests/results; \
	docker run --rm \
		--network hands-system \
		-v "$(PWD)/load_tests:/scripts" \
		-e JWT_TOKEN=$$TOKEN \
		-e BASE_URL=http://traefik \
		grafana/k6:latest run \
		--stage 15s:5 --stage 30s:10 --stage 30s:25 --stage 30s:50 --stage 15s:0 \
		/scripts/k6_script.js; \
	echo "Stress test results saved to load_tests/results/summary.json"

# Restart specific service
restart:
	@if [ -z "$(SERVICE)" ]; then \
		echo "Usage: make restart SERVICE=<service-name>"; \
		echo "Available services: office-api, traefik, vue-frontend, backend-chat, frontend-chat, mysql-db, db-migrate"; \
	else \
		$(COMPOSE) restart $(SERVICE); \
	fi

# ── Local Development ─────────────────────────────────────────────────────────
# No code changes needed — env vars have local defaults, Docker overrides them.
# Prerequisite: brew services start mysql

# Start all services locally:
#   1. MCP servers (skills-urgency, odoo-calendar, google-utils)  — ports 7001-7003
#   2. Agent backend (waits 3s for MCP servers)                   — port 8000
#   3. Office API                                                  — port 9000
#   4. Streamlit chat frontend                                     — port 8501
#   5. Vue admin frontend                                          — port 5173
dev:
	@echo "Starting all services in local mode (MySQL must already be running)..."
	@echo "Press Ctrl+C to stop everything"
	@trap 'kill 0' INT; \
	PYTHONPATH=$(PWD) python -m services.mcp_skills_urgency.server & \
	PYTHONPATH=$(PWD) python -m services.mcp_oddo_calendar.server & \
	PYTHONPATH=$(PWD) python -m services.mcp_google_utils.server & \
	(sleep 3 && PYTHONPATH=$(PWD) uvicorn backend.src.agent.agent:app --host 0.0.0.0 --port 8000 --reload) & \
	PYTHONPATH=$(PWD) uvicorn backend.office.app:app --host 0.0.0.0 --port 9000 --reload & \
	(sleep 5 && streamlit run frontend/src/main.py --server.port=8501) & \
	(cd frontend-vue && npm run dev) & \
	wait

# Start only office API + Vue admin frontend locally
dev-office:
	@echo "Starting MySQL..."
	@brew services start mysql 2>/dev/null || true
	@echo "Waiting for MySQL to be ready..."
	@sleep 3
	@echo "Starting Office API (port 9000) and Vue frontend (port 5173)..."
	@echo "Press Ctrl+C to stop everything"
	@trap 'kill 0' INT; \
	PYTHONPATH=$(PWD) uvicorn backend.office.app:app --host 0.0.0.0 --port 9000 --reload & \
	(sleep 2 && cd frontend-vue && npm run dev) & \
	wait

# Show help
help:
	@echo "HANDS SYSTEM - Make Commands"
	@echo "============================="
	@echo ""
	@echo "Docker mode:"
	@echo "  make build                               - Build all Docker images"
	@echo "  make up                                  - Start entire system in Docker with scaled office-api"
	@echo "  make stop                                - Stop all containers (preserve data)"
	@echo "  make down                                - Stop and remove containers (preserve volumes)"
	@echo "  make clean                               - Remove containers AND volumes (full reset)"
	@echo "  make logs                                - Show logs for key services"
	@echo "  make logs-service SERVICE=<name>         - Show logs for specific service"
	@echo "  make test                                - Run tests"
	@echo "  make loadtest                            - Run k6 load test  (5→10→20 VUs, ~90 s)"
	@echo "  make loadtest-stress                     - Run k6 stress test (up to 50 VUs)"
	@echo "  make restart SERVICE=<name>              - Restart specific service"
	@echo ""
	@echo "Public URLs through Traefik:"
	@echo "  Vue Admin                                - http://localhost"
	@echo "  Office API                               - http://localhost/api"
	@echo "  Auth                                     - http://localhost/auth"
	@echo "  AI Chat Backend                          - http://localhost/chat"
	@echo "  Streamlit Frontend                       - http://localhost/streamlit"
	@echo "  Traefik Dashboard                        - http://localhost:8888"
	@echo ""
	@echo "Local development (no Docker, MySQL must be running):"
	@echo "  make dev                                 - Start all services locally"
	@echo "  make dev-office                          - Start MySQL + office API + Vue frontend locally"
	@echo ""
	@echo "  make help                                - Show this help message"