# Simple Makefile for building TrusSV without cmake.
# Requires: clang++ (system) or g++, and htslib headers+lib.
#
# htslib location: defaults to the active conda environment ($CONDA_PREFIX),
# then Homebrew (/opt/homebrew), then /usr/local. Override explicitly with, e.g.:
#     make HTSLIB_ENV=/opt/homebrew        (Homebrew htslib)
#     make HTSLIB_ENV=/path/to/conda/env   (bioconda htslib)

HTSLIB_ENV ?= $(if $(CONDA_PREFIX),$(CONDA_PREFIX),$(if $(wildcard /opt/homebrew/include/htslib/vcf.h),/opt/homebrew,/usr/local))

CXX       ?= clang++
CXXFLAGS   = -std=c++17 -O2 -Wall -Wextra -Wno-unused-parameter \
             -I$(HTSLIB_ENV)/include -Isrc
LDFLAGS    = -L$(HTSLIB_ENV)/lib -lhts -lz -lbz2 -llzma \
             -Wl,-rpath,$(HTSLIB_ENV)/lib

# OpenMP: auto-enable parallel bucket processing when the compiler supports it
# (e.g. g++, or clang++ with libomp); otherwise fall back to a serial build.
# Force off with `make OPENMP=0`.
OPENMP ?= $(shell printf 'int main(){return 0;}' | \
            $(CXX) -fopenmp -x c++ - -o /dev/null 2>/dev/null && echo 1)
ifeq ($(OPENMP),1)
  CXXFLAGS += -fopenmp -DHAVE_OPENMP=1
  LDFLAGS  += -fopenmp
endif

SRCS = src/main.cpp src/io.cpp src/svtype.cpp src/cluster.cpp \
       src/output.cpp src/distance.cpp

OBJS = $(SRCS:src/%.cpp=build/%.o)

TEST_SRCS = tests/test_distance.cpp tests/test_svtype.cpp tests/test_cluster.cpp
LIB_SRCS  = src/io.cpp src/svtype.cpp src/cluster.cpp src/output.cpp src/distance.cpp
LIB_OBJS  = $(LIB_SRCS:src/%.cpp=build/%.o)

.PHONY: all clean test test-unit test-integration

all: build/trusv

build/trusv: $(OBJS) | build
	$(CXX) $(OBJS) $(LDFLAGS) -o $@

build/%.o: src/%.cpp | build
	$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@

build:
	mkdir -p build

# Include auto-generated header dependencies
-include $(OBJS:.o=.d) $(patsubst tests/%.cpp,build/%.d,$(TEST_SRCS))

# ── Tests ─────────────────────────────────────────────────────────────────────
build/test_distance: build/test_distance.o $(LIB_OBJS) | build
	$(CXX) $^ $(LDFLAGS) -o $@

build/test_svtype: build/test_svtype.o $(LIB_OBJS) | build
	$(CXX) $^ $(LDFLAGS) -o $@

build/test_cluster: build/test_cluster.o $(LIB_OBJS) | build
	$(CXX) $^ $(LDFLAGS) -o $@

build/%.o: tests/%.cpp | build
	$(CXX) $(CXXFLAGS) -c $< -o $@

# Unit tests: fast, synthetic in-memory structs.
test-unit: build/test_distance build/test_svtype build/test_cluster
	build/test_distance
	build/test_svtype
	build/test_cluster

# Integration test: runs the binary on small real fixtures (chr1 slice of the
# HG002 callsets) and checks output invariants. Needs only the built binary.
test-integration: build/trusv
	bash tests/integration.sh

# Full suite.
test: test-unit test-integration

clean:
	rm -rf build
