# Semana 11: árboles AVL. Se usa dentro del entorno del curso.
#
#   make               compila los programas de la clase en build/
#   make lab           compila el laboratorio en build/lab/
#   make test          corre las pruebas de los ejemplos y de los apuntes
#   make test-base     comprueba el mapa de partida, que no depende del balance
#   make test-rotations  prueba update_height y las rotaciones (paso 1)
#   make test-insert   prueba la inserción con balance y check_invariants (paso 2)
#   make test-erase    prueba el borrado con balance, contra std::map (paso 3)
#   make test-lab      prueba todo su laboratorio; falla hasta que lo terminen
#   make bench         mide su mapa, con -O2 y sin sanitizers (paso 4)
#   make clean         borra lo generado
#
# Los programas de errors/ tienen errores a propósito. No se compilan con make:
# los compilan las pruebas, y ustedes, con los comandos de los apuntes.

CXX = g++
CXXFLAGS = -Wall -Wextra -std=c++20 -g -fsanitize=address,undefined
BENCHFLAGS = -Wall -Wextra -std=c++20 -O2
DATA ?= ../../data
LAB_DIR ?= lab
BUILD = build
PROGRAMS = avl_trace rotation_demo min_nodes test_structures
BENCHES = all_orders height_table repair_counts avl_times dictionary_avl
COMMON_HEADERS = avl_set.h plain_tree.h fibonacci_tree.h bench.h
LAB_HEADERS = $(LAB_DIR)/avl_map.h lab/not_implemented.h fibonacci_tree.h

.PHONY: all lab test test-base test-rotations test-insert test-erase test-lab bench clean

all: $(PROGRAMS:%=$(BUILD)/%) $(BENCHES:%=$(BUILD)/%)

$(PROGRAMS:%=$(BUILD)/%): $(BUILD)/%: %.cpp $(COMMON_HEADERS) | $(BUILD)
	$(CXX) $(CXXFLAGS) $< -o $@

# Las mediciones van con -O2 y sin sanitizers.
$(BENCHES:%=$(BUILD)/%): $(BUILD)/%: %.cpp $(COMMON_HEADERS) | $(BUILD)
	$(CXX) $(BENCHFLAGS) $< -o $@

# LAB_DIR va primero: así las pruebas toman el mapa de esa carpeta.
$(BUILD)/$(LAB_DIR)/map_tests: lab/tests/map_tests.cpp $(LAB_HEADERS) | $(BUILD)/$(LAB_DIR)
	$(CXX) $(CXXFLAGS) -I$(LAB_DIR) -Ilab -I. $< -o $@

$(BUILD)/$(LAB_DIR)/bench_avl: lab/tests/bench_avl.cpp $(LAB_HEADERS) plain_tree.h bench.h | $(BUILD)/$(LAB_DIR)
	$(CXX) $(BENCHFLAGS) -I$(LAB_DIR) -Ilab -I. $< -o $@

$(BUILD) $(BUILD)/$(LAB_DIR):
	mkdir -p $@

lab: $(BUILD)/$(LAB_DIR)/map_tests $(BUILD)/$(LAB_DIR)/bench_avl

# Si existe solution/, también se comprueba la solución del laboratorio.
test: all
	@if [ -d solution ]; then $(MAKE) --no-print-directory LAB_DIR=solution lab; fi
	DATA=$(DATA) python3 -m unittest discover -p 'test_*.py'

test-base: all lab
	LAB_DIR=$(LAB_DIR) python3 -m unittest -v test_lab.TestBase

test-rotations: all lab
	LAB_DIR=$(LAB_DIR) python3 -m unittest -v test_lab.TestRotations

test-insert: all lab
	LAB_DIR=$(LAB_DIR) python3 -m unittest -v test_lab.TestInsert

test-erase: all lab
	LAB_DIR=$(LAB_DIR) python3 -m unittest -v test_lab.TestErase

test-lab: all lab
	LAB_DIR=$(LAB_DIR) python3 -m unittest -v test_lab

bench: $(BUILD)/$(LAB_DIR)/bench_avl
	$<

clean:
	rm -rf $(BUILD) __pycache__
