#===============================================================================
# Makefile for runSNVS -- Shell-Nested Virtual Spaces (Fortran 2008 + a little C)
#
# Builds ONE native executable for the machine it runs on:
#
#   Linux          gfortran + OpenBLAS/LAPACK (Debian/Ubuntu: libopenblas-dev liblapack-dev)
#   macOS          Homebrew gfortran + Accelerate (GCC runtime folded in)
#   Windows        MSYS2 shell (UCRT64 or MINGW64): pacman gcc-fortran + openblas;
#                  the executable is runSNVS.exe, win_utf8.o sets the console to
#                  UTF-8; `make STATIC=1` folds every DLL in so the .exe also runs
#                  from cmd.exe/PowerShell outside the MSYS2 shell.
#
# libcint (two-electron integral library, Apache-2.0) is built OUTSIDE the tree by
# scripts/build_libcint.sh and linked STATICALLY when $(LIBCINT)/lib/libcint.a
# exists -- the default of that script -- so the executable carries no rpath and
# no DLL dependency. A shared libcint is used only as a fallback
# (LIBCINT_LINK=shared), with an rpath on Linux/macOS.
#
# Targets:
#   make            - Build runSNVS (default, -march=native)
#   make deps       - Regenerate build/deps.mk from the `use` statements
#   make clean      - Remove build artifacts
#   make install    - Install runSNVS (default /usr/local/bin; may need sudo;
#                     in MSYS2 the default prefix is $MINGW_PREFIX)
#   make uninstall  - Remove the installed runSNVS
#   make help       - Show this message
#
# Options:
#   BUILD_DATE=YYYY-Mon-DD  - Override the banner build date (default: today).
#                             Two builds of the same sources with the same date
#                             are byte-identical.
#   FC=...                  - Fortran compiler (default gfortran)
#   PREFIX=/path            - Install prefix (default /usr/local; MSYS2: $MINGW_PREFIX)
#   BINDIR=/path            - Executable directory (default $(PREFIX)/bin)
#   DESTDIR=/path           - Optional staging root for packaging
#   LIBCINT=/path           - libcint install prefix (default ~/opt/libcint-6.1.3)
#   LIBCINT_LINK=static|shared - default: static when lib/libcint.a exists
#   STATIC=1                - Windows only: fully static executable (-static)
#
# Module dependencies are GENERATED (scripts/gen_deps.sh -> build/deps.mk) from
# the `use snvs_*` lines of every source file, so every .o rule carries its
# complete prerequisite set and `make -j` is safe. OBJECTS below is still kept
# in topological order for readability and for a fallback serial build.
#===============================================================================

CC = cc
BUILD_DATE := $(shell date +"%Y-%b-%d")

UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)

# -ffpe-summary=none: silence gfortran's exit-time IEEE flag summary (raised
# harmlessly inside LAPACK on near-singular overlap matrices of diffuse bases).
# Host detection. MSYS2 shells report uname -s as MINGW64_NT-.../UCRT64_NT-...
# and always export OS=Windows_NT, which is what we key on.
EXE_SUFFIX =
ifeq ($(OS),Windows_NT)
    HOST = windows
    EXE_SUFFIX = .exe
    FC = gfortran
    FFLAGS  = -O3 -march=native -Wall -Wextra -std=f2008 -ffree-line-length-none -cpp -fopenmp -ffpe-summary=none -DBUILD_DATE='"$(BUILD_DATE)"'
    # MSYS2's mingw-w64-*-openblas ships LAPACK inside libopenblas. STATIC=1
    # links every runtime (gfortran, gomp, winpthread, openblas) into the .exe.
    ifeq ($(STATIC),1)
        LDFLAGS = -static -lopenblas -lpthread -fopenmp
    else
        LDFLAGS = -lopenblas -lpthread -fopenmp -static-libgfortran -static-libgcc -static-libquadmath
    endif
else ifeq ($(UNAME_S),Darwin)
    HOST = macos
    ifeq ($(UNAME_M),arm64)
        BREW_PREFIX := /opt/homebrew
    else
        BREW_PREFIX := /usr/local
    endif
    FC = $(firstword $(wildcard $(BREW_PREFIX)/bin/gfortran) gfortran)
    FFLAGS  = -O3 -march=native -Wall -Wextra -std=f2008 -ffree-line-length-none -cpp -fopenmp -ffpe-summary=none -D__APPLE__ -DBUILD_DATE='"$(BUILD_DATE)"'
    LDFLAGS = -framework Accelerate -fopenmp \
              -static-libgfortran -static-libgcc -static-libquadmath
else
    HOST = linux
    FC = gfortran
    FFLAGS  = -O3 -march=native -Wall -Wextra -std=f2008 -ffree-line-length-none -cpp -fopenmp -ffpe-summary=none -DBUILD_DATE='"$(BUILD_DATE)"'
    # OpenBLAS first (multithreaded LAPACK); reference -llapack as fallback.
    # BLAS=openmp (stage R6) links the OpenMP flavour of OpenBLAS (Debian: libopenblas0-openmp), whose workers
    # sleep inside OpenMP regions; the default pthread flavour needs the set_blas_parallel_mode guards (3 X 2026).
    # (The OpenMP flavour is less tested than the default pthread one.)
    ifeq ($(BLAS),openmp)
    OPENBLAS_OMP_DIR ?= /usr/lib/x86_64-linux-gnu/openblas-openmp
    LDFLAGS = -L$(OPENBLAS_OMP_DIR) -Wl,-rpath,$(OPENBLAS_OMP_DIR) -lopenblas -llapack -lpthread -fopenmp
    else
    LDFLAGS = -lopenblas -llapack -lpthread -fopenmp
    endif
endif

# libcint (two-electron integral kernel of the RI-MP2 lane, 2026-09-25).
# Built OUTSIDE the project (Apache-2.0, C) by scripts/build_libcint.sh; default
# prefix ~/opt/libcint-6.1.3, override with `make LIBCINT=/path/to/prefix`.
# Static archive preferred (self-contained executable, no rpath, no DLL);
# shared fallback records the library directory as an rpath (Linux/macOS).
LIBCINT ?= $(HOME)/opt/libcint-6.1.3
LIBCINT_LINK ?= $(if $(wildcard $(LIBCINT)/lib/libcint.a),static,shared)
ifeq ($(LIBCINT_LINK),static)
    LDFLAGS += $(LIBCINT)/lib/libcint.a -lm
else ifeq ($(HOST),windows)
    LDFLAGS += -L$(LIBCINT)/lib -lcint
else
    LDFLAGS += -L$(LIBCINT)/lib -Wl,-rpath,$(LIBCINT)/lib -lcint
endif

SRC_DIR   = src
BUILD_DIR = build
MAIN_EXE  = runSNVS$(EXE_SUFFIX)

# DESTDIR supports staged installs
# without changing the final prefix; quote paths so staging roots may contain spaces.
ifeq ($(HOST),windows)
    PREFIX ?= $(if $(MINGW_PREFIX),$(MINGW_PREFIX),/usr/local)
else
    PREFIX ?= /usr/local
endif
BINDIR ?= $(PREFIX)/bin
DESTDIR ?=

# Module set, topological order.
OBJECTS = $(BUILD_DIR)/snvs_precision.o \
          $(BUILD_DIR)/snvs_interface.o \
          $(BUILD_DIR)/snvs_citations.o \
          $(BUILD_DIR)/snvs_types.o \
          $(BUILD_DIR)/snvs_output_request.o \
          $(BUILD_DIR)/snvs_linalg.o \
          $(BUILD_DIR)/snvs_gates.o \
          $(BUILD_DIR)/snvs_fast_parse_c.o \
          $(BUILD_DIR)/win_utf8.o \
          $(BUILD_DIR)/snvs_fast_parse.o \
          $(BUILD_DIR)/snvs_wavefunction.o \
          $(BUILD_DIR)/snvs_overlap.o \
          $(BUILD_DIR)/snvs_cint.o \
          $(BUILD_DIR)/snvs_fock_exact.o \
          $(BUILD_DIR)/snvs_riaux.o \
          $(BUILD_DIR)/snvs_primtensor.o \
          $(BUILD_DIR)/snvs_lmp2dom.o \
          $(BUILD_DIR)/snvs_cc_types.o \
          $(BUILD_DIR)/snvs_cc_ints.o \
          $(BUILD_DIR)/snvs_cc_uints.o \
          $(BUILD_DIR)/snvs_cc_ao.o \
          $(BUILD_DIR)/snvs_cc_triples.o \
          $(BUILD_DIR)/snvs_cc_utriples.o \
          $(BUILD_DIR)/snvs_ccsd_rhf.o \
          $(BUILD_DIR)/snvs_ccsd_uhf.o \
          $(BUILD_DIR)/snvs_rimp2.o \
          $(BUILD_DIR)/snvs_nao_types.o \
          $(BUILD_DIR)/snvs_nao_elements.o \
          $(BUILD_DIR)/snvs_nao_orth.o \
          $(BUILD_DIR)/snvs_parser_fchk.o \
          $(BUILD_DIR)/snvs_parser_json.o \
          $(BUILD_DIR)/snvs_parser_molden.o \
          $(BUILD_DIR)/snvs_cli_parser.o \
          $(BUILD_DIR)/snvs_parser_turbomole.o \
          $(BUILD_DIR)/snvs_parser_gamess.o \
          $(BUILD_DIR)/snvs_input.o \
          $(BUILD_DIR)/snvs_scf_input.o \
          $(BUILD_DIR)/snvs_dft_grid.o \
          $(BUILD_DIR)/snvs_ad2.o \
          $(BUILD_DIR)/snvs_xc.o \
          $(BUILD_DIR)/snvs_cube_grid.o \
          $(BUILD_DIR)/snvs_grid_batch.o \
          $(BUILD_DIR)/snvs_cosx_kernel.o \
          $(BUILD_DIR)/snvs_cosx.o \
          $(BUILD_DIR)/snvs_ks.o \
          $(BUILD_DIR)/snvs_rijmp.o \
          $(BUILD_DIR)/snvs_scf.o \
          $(BUILD_DIR)/snvs_scf_bridge.o \
          $(BUILD_DIR)/snvs_nao_debug.o \
          $(BUILD_DIR)/snvs_ano_data.o \
          $(BUILD_DIR)/snvs_ano_guide.o \
          $(BUILD_DIR)/snvs_iano.o \
          $(BUILD_DIR)/snvs_nao_driver.o \
          $(BUILD_DIR)/snvs_density.o \
          $(BUILD_DIR)/snvs_spin_spaces.o \
          $(BUILD_DIR)/snvs_spin_hierarchy.o \
          $(BUILD_DIR)/snvs_hierarchy.o \
          $(BUILD_DIR)/snvs_output_cube.o \
          $(BUILD_DIR)/snvs_output_json.o \
          $(BUILD_DIR)/snvs_ecp_check.o

.PHONY: all clean help deps install uninstall

all: $(MAIN_EXE)

$(MAIN_EXE): $(OBJECTS) $(BUILD_DIR)/snvs_main.o
	@echo ""
	@echo "Linking $@..."
	$(FC) $(FFLAGS) -o $@ $^ $(LDFLAGS)
	@echo "Build complete: $@"
	@echo ""

$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# C helper (strtod-based token reader; ~15x faster than list-directed read).
$(BUILD_DIR)/snvs_fast_parse_c.o: $(SRC_DIR)/snvs_fast_parse.c | $(BUILD_DIR)
	@echo "Compiling $<..."
	$(CC) -O3 -Wall -c $< -o $@

# Windows console UTF-8 constructor; compiles to an empty object elsewhere.
$(BUILD_DIR)/win_utf8.o: $(SRC_DIR)/win_utf8.c | $(BUILD_DIR)
	@echo "Compiling $<..."
	$(CC) -O2 -Wall -c $< -o $@

# Generic Fortran rule; the inter-module prerequisites come from deps.mk.
# -I$(SRC_DIR): Fortran INCLUDE of the generated table file(s) in src/.
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.f90 | $(BUILD_DIR)
	@echo "Compiling $<..."
	$(FC) $(FFLAGS) -c $< -o $@ -J$(BUILD_DIR) -I$(BUILD_DIR) -I$(SRC_DIR)

# Exact Cartesian<->spherical tables (double literals; see snvs_overlap.f90).
$(BUILD_DIR)/snvs_overlap.o: $(SRC_DIR)/snvs_c2s_tables.inc
$(BUILD_DIR)/snvs_riaux.o: $(SRC_DIR)/snvs_def2j_data.inc

# Lebedev angular tables and atomic radii of the DFT grids (SCF-4).
$(BUILD_DIR)/snvs_dft_grid.o: $(SRC_DIR)/snvs_lebedev_tables.inc $(SRC_DIR)/snvs_grid_radii.inc

# snvs_fast_parse.f90 binds to the C object.
$(BUILD_DIR)/snvs_fast_parse.o: $(BUILD_DIR)/snvs_fast_parse_c.o

# Generated dependency graph (use-statements -> .o prerequisites).
$(BUILD_DIR)/deps.mk: $(wildcard $(SRC_DIR)/*.f90) scripts/gen_deps.sh | $(BUILD_DIR)
	@sh scripts/gen_deps.sh $(SRC_DIR) $(BUILD_DIR) > $@

deps: $(BUILD_DIR)/deps.mk
	@echo "Dependencies written to $(BUILD_DIR)/deps.mk"

ifneq ($(MAKECMDGOALS),clean)
-include $(BUILD_DIR)/deps.mk
endif

clean:
	@echo "Cleaning build artifacts..."
	rm -rf $(BUILD_DIR)/*.o $(BUILD_DIR)/*.mod $(BUILD_DIR)/deps.mk
	rm -f $(MAIN_EXE) *.mod
	@echo "Clean complete"

install: $(MAIN_EXE)
	@echo "Installing $(MAIN_EXE) to $(DESTDIR)$(BINDIR)..."
	install -d "$(DESTDIR)$(BINDIR)"
	install -m 755 "$(MAIN_EXE)" "$(DESTDIR)$(BINDIR)/$(MAIN_EXE)"
	@echo "Installation complete. Make sure $(BINDIR) is in your PATH."


uninstall:
	@echo "Removing $(MAIN_EXE) from $(DESTDIR)$(BINDIR)..."
	rm -f "$(DESTDIR)$(BINDIR)/$(MAIN_EXE)"
	@echo "Uninstallation complete."

help:
	@echo ""
	@echo "runSNVS - Shell-Nested Virtual Spaces (Fortran 2008)"
	@echo ""
	@echo "  make [-j N]       - Build runSNVS (native; Linux, macOS, Windows/MSYS2)"
	@echo "  make deps         - Regenerate build/deps.mk"
	@echo "  make clean        - Remove build artifacts"
	@echo "  make install      - Install to /usr/local/bin (may need sudo)"
	@echo "  make uninstall    - Remove the installed executable"
	@echo "  make help         - Show this message"
	@echo ""
	@echo "  BUILD_DATE=YYYY-Mon-DD  - Override the banner/build date"
	@echo "  FC=<compiler>           - Fortran compiler (default gfortran)"
	@echo "  PREFIX=<path>           - Install prefix (default /usr/local)"
	@echo "  BINDIR=<path>           - Executable directory (default PREFIX/bin)"
	@echo "  DESTDIR=<path>          - Optional staging root for packaging"
	@echo "  LIBCINT=<path>          - libcint prefix (default ~/opt/libcint-6.1.3)"
	@echo "  LIBCINT_LINK=static|shared - default static when lib/libcint.a exists"
	@echo "  STATIC=1                - Windows (MSYS2): fully static runSNVS.exe"
	@echo ""
	@echo "  Host: $(HOST)   libcint: $(LIBCINT_LINK) ($(LIBCINT))"
	@echo ""
