.PHONY: help serve stop test clean install

# Default target
help:
	@echo "Proxym Makefile"
	@echo ""
	@echo "Available commands:"
	@echo "  serve      - Start the proxy server (default port 4000)"
	@echo "  stop       - Stop all running proxy servers"
	@echo "  test       - Run all tests"
	@echo "  test-gui   - Run GUI tests only"
	@echo "  clean      - Clean cache and temp files"
	@echo "  install    - Install dependencies"
	@echo "  dev        - Start development server with reload"

# Start server
serve:
	@echo "Starting Proxym server..."
	.venv/bin/proxym serve

# Start server on specific port
serve-port:
	@if [ -z "$(PORT)" ]; then echo "Usage: make serve-port PORT=4001"; exit 1; fi
	@echo "Starting Proxym server on port $(PORT)..."
	.venv/bin/proxym serve --port $(PORT)

# Development server with reload
dev:
	@echo "Starting development server with reload..."
	.venv/bin/proxym serve --reload --port $$(.venv/bin/python -c "from proxym.config import get_settings; print(get_settings().dev_port)")

# Development server (alias)
dev-serve: dev

# Stop all running servers
stop:
	@echo "Stopping all Proxym servers..."
	@pkill -f "proxym serve" || true
	@pkill -f "proxym.*serve" || true
	@pkill -f "python.*proxym" || true
	@echo "Checking for remaining processes..."
	@ps aux | grep -v grep | grep proxym || echo "No Proxym processes found"

# Force stop (kill on port)
stop-port:
	@if [ -z "$(PORT)" ]; then echo "Usage: make stop-port PORT=4001"; exit 1; fi
	@echo "Stopping server on port $(PORT)..."
	@fuser -k $(PORT)/tcp 2>/dev/null || true
	@lsof -ti:$(PORT) | xargs kill -9 2>/dev/null || true
	@echo "Port $(PORT) cleared"

# Check what's running
status:
	@echo "Checking running Proxym processes..."
	@ps aux | grep -v grep | grep proxym || echo "No Proxym processes found"
	@echo ""
	@echo "Checking ports 4000-4002..."
	@netstat -tlnp 2>/dev/null | grep ":400[0-2]" || echo "No servers on ports 4000-4002"

# Run tests
test:
	@echo "Running all tests..."
	.venv/bin/python -m pytest tests/ -v

# Run GUI tests only
test-gui:
	@echo "Running GUI tests..."
	.venv/bin/python -m pytest tests/test_dashboard_gui.py -v

# Run live tests
test-live:
	@echo "Running live tests..."
	.venv/bin/python -m pytest tests/test_dashboard_live.py -v

# Install dependencies
install:
	@echo "Installing dependencies..."
	python -m venv .venv || true
	.venv/bin/pip install -e ".[dev]"
	.venv/bin/playwright install || true

# Clean cache and temp files
clean:
	@echo "Cleaning cache..."
	find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
	find . -type f -name "*.pyc" -delete 2>/dev/null || true
	rm -rf .pytest_cache 2>/dev/null || true
	rm -rf .coverage 2>/dev/null || true
	rm -rf htmlcov 2>/dev/null || true
	@echo "Cache cleaned"

# Quick restart
restart: stop serve

# Development setup
setup: install
	@echo "Setup complete. Use 'make dev' to start development server."
