.PHONY: help up down serve stop test clean install dev test-unit test-int test-e2e test-smoke test-tickets test-all health-check lint format watch vm-create vm-list coverage vscode-up vscode-down vscode-logs vscode-build vscode-open stack-up stack-down check-dashboard

# Default target
help:
	@echo "Proxym Makefile"
	@echo ""
	@echo "Docker commands:"
	@echo "  up            - Start all Docker services (proxym + redis)"
	@echo "  down          - Stop all Docker services"
	@echo ""
	@echo "Server commands:"
	@echo "  serve         - Start the proxy server (default port 4000)"
	@echo "  serve-port    - Start on specific port (PORT=4001)"
	@echo "  dev           - Start development server with reload in Docker"
	@echo "  stop          - Stop Docker services for proxym"
	@echo "  stop-port     - Stop server on specific port (PORT=4001)"
	@echo "  restart       - Restart the server"
	@echo "  status        - Check running processes"
	@echo ""
	@echo "Test commands:"
	@echo "  test          - Run all tests"
	@echo "  test-unit     - Run unit tests only (fast)"
	@echo "  test-int      - Run integration tests"
	@echo "  test-e2e      - Run E2E tests"
	@echo "  test-smoke    - Run smoke tests (tool health)"
	@echo "  test-tickets  - Run ticket-related tests"
	@echo "  test-all      - Run all tests with coverage"
	@echo "  test-gui      - Run GUI tests only"
	@echo "  check-dashboard - Run dashboard live checks + GUI tests"
	@echo "  test-live     - Run live tests"
	@echo "  test-watch    - Run tests in watch mode (TDD)"
	@echo "  health-check  - Quick curl-based health check"
	@echo "  coverage      - Generate coverage report"
	@echo ""
	@echo "Code quality:"
	@echo "  lint          - Run ruff and mypy checks"
	@echo "  format        - Format code with ruff"
	@echo ""
	@echo "VM commands:"
	@echo "  vm-list       - List all VMs"
	@echo "  vm-create     - Create new VM (interactive)"
	@echo "  vm-start      - Start VM (VM=name)"
	@echo "  vm-stop       - Stop VM (VM=name)"
	@echo ""
	@echo "VS Code Web commands:"
	@echo "  vscode-up     - Start VS Code Web (http://localhost:8080)"
	@echo "  vscode-down   - Stop VS Code Web"
	@echo "  vscode-logs   - Show VS Code Web logs"
	@echo "  vscode-build  - Rebuild VS Code Web image"
	@echo "  vscode-open   - Open VS Code Web in browser"
	@echo "  stack-up      - Start full stack (proxym + redis + vscode + open-webui)"
	@echo "  stack-down    - Stop full stack"
	@echo ""
	@echo "Other commands:"
	@echo "  install       - Install dependencies"
	@echo "  setup         - Setup development environment"
	@echo "  clean         - Clean cache and temp files"
	@echo "  watch         - Start file watcher for context updates"
	@echo "  metrics       - Generate code metrics"

# 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 in Docker..."
	@DEV_PORT=$$(grep -m1 '^DEV_PORT=' .env 2>/dev/null | cut -d= -f2 | grep . || echo 4001); \
	AI_PORT=$$(grep -m1 '^AI_PROXY_PORT=' .env 2>/dev/null | cut -d= -f2 | grep . || echo 4000); \
	echo "DEV_PORT=$$DEV_PORT AI_PROXY_PORT=$$AI_PORT"; \
	docker compose --profile dev up -d redis proxy-dev; \
	echo "✅ Development service started on http://localhost:$$DEV_PORT"; \
	echo "   Use 'docker compose logs -f proxy-dev' to follow logs if needed"
	@docker compose --profile dev logs -f --tail=100 proxy-dev

# Development server (alias)
dev-serve: dev

# Stop all running servers
stop:
	@echo "Stopping Proxym Docker services..."
	@docker compose --profile dev stop proxy proxy-dev redis || true
	@docker compose --profile vscode stop vscode || true
	@docker compose --profile webui stop open-webui || true
	@docker compose ps

# 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 containers..."
	@docker compose --profile dev --profile vscode --profile webui ps
	@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 unit tests only (fast)
test-unit:
	@echo "Running unit tests..."
	.venv/bin/python -m pytest tests/ \
	  --ignore=tests/test_e2e.py \
	  --ignore=tests/test_dashboard_live.py \
	  --ignore=tests/test_dashboard_performance.py \
	  --ignore=tests/gui/ \
	  -q --tb=short -x

# Run integration tests
test-int:
	@echo "Running integration tests..."
	docker compose up -d redis 2>/dev/null || echo "Redis not available, continuing..."
	.venv/bin/python -m pytest tests/test_dashboard_integration.py \
	   tests/test_api_completions.py \
	   tests/test_api_system.py \
	   tests/test_api_context.py \
	   -v --tb=short

# Run E2E tests
test-e2e:
	@echo "Running E2E tests..."
	.venv/bin/python -m pytest tests/test_e2e.py tests/test_dashboard_live.py -v --timeout=300

# Run tests in watch mode (TDD)
test-watch:
	@echo "Running tests in watch mode..."
	.venv/bin/python -m pytest_watch tests/ -- -q --tb=short

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

# Check dashboard UI + GUI tests
check-dashboard:
	@echo "Checking dashboard UI and GUI tests..."
	bash scripts/check_dashboard.sh

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

# Run smoke tests (tool health checks)
test-smoke:
	@echo "Running smoke tests..."
	.venv/bin/python -m pytest tests/test_tool_health.py -v --timeout=60

# Quick health check via curl
health-check:
	@BASE=$$(grep -m1 'AI_PROXY_PORT=' .env 2>/dev/null | cut -d= -f2 | grep . || echo 4000); \
	echo "Checking proxym on port $$BASE..."; \
	curl -sf "http://localhost:$$BASE/health" | python -m json.tool && echo "✅ Healthy" || echo "❌ Not reachable"

# Run ticket-related tests
test-tickets:
	@echo "Running ticket tests..."
	.venv/bin/python -m pytest tests/test_tickets.py tests/test_project_e2e.py -v

# Run all tests (alias with coverage)
test-all:
	@echo "Running all tests with coverage..."
	.venv/bin/python -m pytest tests/ \
	  --ignore=tests/test_e2e.py \
	  --ignore=tests/test_dashboard_live.py \
	  --ignore=tests/test_dashboard_performance.py \
	  --cov=src/proxym \
	  --cov-report=term-missing \
	  -v --timeout=60

# Generate coverage report
coverage:
	@echo "Generating coverage report..."
	.venv/bin/python -m pytest tests/ \
	  --ignore=tests/test_e2e.py \
	  --ignore=tests/test_dashboard_live.py \
	  --cov=src/proxym \
	  --cov-report=html \
	  --cov-report=term-missing
	@echo "Coverage report: htmlcov/index.html"

# Run linting
lint:
	@echo "Running linters..."
	.venv/bin/ruff check src/ tests/
	.venv/bin/mypy src/proxym --ignore-missing-imports

# Format code
format:
	@echo "Formatting code..."
	.venv/bin/ruff format src/ tests/

# VM commands
vm-list:
	@echo "Listing VMs..."
	.venv/bin/proxym vm list

vm-create:
	@read -p "VM name: " name; \
	 read -p "Tool (windsurf/cursor/vscode): " tool; \
	 read -p "Account ID: " account; \
	 .venv/bin/proxym vm create --name $$name --tool $$tool --account $$account

vm-start:
	@if [ -z "$(VM)" ]; then echo "Usage: make vm-start VM=windsurf-work"; exit 1; fi
	.venv/bin/proxym vm start $(VM)

vm-stop:
	@if [ -z "$(VM)" ]; then echo "Usage: make vm-stop VM=windsurf-work"; exit 1; fi
	.venv/bin/proxym vm stop $(VM)

# Start file watcher for context updates
watch:
	@echo "Starting file watcher..."
	.venv/bin/proxym watch $(PWD) --push-to http://localhost:4000

# Generate code metrics
metrics:
	@echo "Generating code metrics..."
	@which code2llm >/dev/null 2>&1 && code2llm ./ -f all -o ./project --no-chunk || echo "code2llm not installed"
	@echo "Metrics in ./project/"

# 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"

# ── Docker compose ─────────────────────────────────────────────
up:
	docker compose up -d
	@echo "✅ Services started"
	@echo "   proxym: http://localhost:$$(grep -m1 AI_PROXY_PORT .env 2>/dev/null | cut -d= -f2 | grep . || echo 4000)"

down:
	docker compose --profile dev --profile vscode --profile webui down --remove-orphans

# Quick restart
restart: down up

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

# ── VS Code Web ────────────────────────────────────────────────
vscode-up:
	@echo "Starting VS Code Web..."
	docker compose --profile vscode up -d vscode
	@echo "✅ VS Code Web → http://localhost:$$(grep -m1 VSCODE_PORT .env 2>/dev/null | cut -d= -f2 | grep . || echo 8080)"

vscode-down:
	docker compose --profile vscode stop vscode

vscode-logs:
	docker compose --profile vscode logs -f --tail=100 vscode

vscode-build:
	docker compose --profile vscode build --no-cache vscode

vscode-open:
	@PORT=$$(grep -m1 VSCODE_PORT .env 2>/dev/null | cut -d= -f2 | grep . || echo 8080); \
		xdg-open "http://localhost:$$PORT" 2>/dev/null \
		|| open "http://localhost:$$PORT" 2>/dev/null \
		|| echo "Open http://localhost:$$PORT in your browser"

# ── Full stack (proxym + redis + vscode + open-webui) ──────────
stack-up:
	docker compose --profile vscode --profile webui up -d
	@echo "✅ Full stack started"
	@echo "   proxym:     http://localhost:$$(grep -m1 AI_PROXY_PORT .env 2>/dev/null | cut -d= -f2 | grep . || echo 4000)"
	@echo "   VS Code:    http://localhost:$$(grep -m1 VSCODE_PORT .env 2>/dev/null | cut -d= -f2 | grep . || echo 8080)"
	@echo "   Open WebUI: http://localhost:$$(grep -m1 OPEN_WEBUI_PORT .env 2>/dev/null | cut -d= -f2 | grep . || echo 3000)"

stack-down:
	docker compose --profile vscode --profile webui down
