import os
import sys
import glob

env = Environment(ENV=os.environ)
# conf = Configure(env)
# print conf.CheckLib('yaml-cpp')

# profiling (uh, i think, it's been a while): '-pg', '-g',
# increase compile time verbosity (e.g. figure out include paths): , '--verbose'
# increase link time verbosity (e.g. figure out lib paths):, '-Wl,--verbose'
env.Append(CPPFLAGS =  ['-O3', '-Wall', '-Wextra', '-pedantic'])  # NOTE -std=c++11 goes in CXXFLAGS (C++ only), not CPPFLAGS, else it's applied to the C source fast_math.c too (gcc warns, but clang/macOS errors: "'-std=c++11' not allowed with 'C'")
env.Append(CXXFLAGS = ['-std=c++11'])
env.Append(LINKFLAGS = ['-O3', '-std=c++11'])
env.Append(CPPPATH = ['../include'])

# Add Homebrew paths for macOS (especially ARM64 which uses /opt/homebrew)
if sys.platform == 'darwin':
    # Check for ARM64 Mac Homebrew path first, then Intel Mac path
    homebrew_paths = ['/opt/homebrew', '/usr/local']
    for homebrew_path in homebrew_paths:
        if os.path.exists(homebrew_path + '/include'):
            env.Append(CPPPATH = [homebrew_path + '/include'])
            env.Append(LIBPATH = [homebrew_path + '/lib'])
            break

env.Append(CPPDEFINES={'STATE_MAX':'500', 'SIZE_MAX':r'\(\(size_t\)-1\)', 'PI':'3.1415926535897932', 'EPS':'1e-6'})  # maybe reduce the state max to something reasonable?

binary_names = ['bcrham', 'hample']

sources = []
for fname in glob.glob(os.getenv('PWD') + '/src/*.cc'):
    is_binary = False
    for bname in binary_names:
        if bname in fname:
            is_binary = True
            break
    if not is_binary:
        # sources.append(fname.replace('src/', '_build/'))
        sources.append(fname)  # seems to work fine this was as well for me, and in this issue someone had it break with the previous line https://github.com/psathyrella/ham/issues/16

# fast_math.c — C source (the env's *.cc glob above does not pick it up).
# Built with -ffp-contract=off so the linear-interp arithmetic in
# fast_softplus is bit-deterministic across compilers (and matches the
# Zig mirror at packages/zig-core/src/ham/fast_math.c). The other ham
# sources don't carry that flag because they don't need cross-backend
# bit equality.
fast_math_c = os.path.join(os.getenv('PWD'), 'src', 'fast_math.c')
fast_math_obj = env.Object(
    target='fast_math',
    source=fast_math_c,
    CCFLAGS=['-O3', '-ffp-contract=off', '-fno-builtin'],
)
sources.append(fast_math_obj)

env.Library(target='ham', source=sources)

for bname in binary_names:
    env.Program(target='../' + bname, source=bname + '.cc', LIBS=['ham', 'yaml-cpp', 'gsl', 'gslcblas'], LIBPATH=['.'] + env.get('LIBPATH', []))
