import os
import subprocess
from shutil import copy, which

import libtbx.load_env

def detect_architecture(verbose=True):
  if verbose:
    print('Looking for GPUs ...')
  available_gpu = subprocess.check_output(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'])
  available_gpu = available_gpu.split(b'\n')
  first_entry = available_gpu[0].decode('utf8')
  if len(first_entry)>0:
    if verbose:
      print( ' Found ', first_entry)
    if 'A100' in first_entry:
      architecture = "Ampere80"
    else:
      architecture = "Volta70"
  else:
    architecture = "HSW"
  return architecture

class system_config(object):
  def __init__(self, host_variable, host_name):
    self.host_variable = host_variable
    self.host_name = host_name
    self.env = {}

  def is_host(self):
    return (self.host_name==os.getenv(self.host_variable))

  def get_copy(self):
    clone = system_config(self.host_variable, self.host_name)
    clone.env = dict(self.env)
    return clone

cfg_default = system_config(host_variable = 'NO_WHERE', host_name='N/A')
cfg_default.env['KOKKOS_DEVICES'] = "OpenMP"
cfg_default.env['KOKKOS_ARCH'] = "HSW"
cfg_default.env['KOKKOS_CUDA_OPTIONS'] = ""
cfg_default.env['LDFLAGS'] = "-Llib"
cfg_default.env['LDLIBS'] = "-lkokkos -ldl"
cfg_default.env['CXX'] = os.environ.get('CXX', 'g++')

list_cfg = []

cfg_corigpu = cfg_default.get_copy()
cfg_corigpu.host_variable = 'NERSC_HOST'
cfg_corigpu.host_name = 'cori'
cfg_corigpu.env['KOKKOS_DEVICES'] = "Cuda"
cfg_corigpu.env['KOKKOS_ARCH'] = "Volta70"
cfg_corigpu.env['KOKKOS_CUDA_OPTIONS'] = "enable_lambda,force_uvm"
cfg_corigpu.env['LDFLAGS'] += " -L$(CUDA_HOME)/lib64"
cfg_corigpu.env['LDLIBS'] += " -lcudart -lcuda"
cfg_corigpu.env['CXX'] = ''
list_cfg.append(cfg_corigpu)

cfg_perlmutter = cfg_corigpu.get_copy()
cfg_perlmutter.host_name = 'perlmutter'
cfg_perlmutter.env['KOKKOS_ARCH'] = 'Ampere80'
list_cfg.append(cfg_perlmutter)

cfg_spock = cfg_default.get_copy()
cfg_spock.host_variable = 'LMOD_SYSTEM_NAME'
cfg_spock.host_name = 'spock'
cfg_spock.env['KOKKOS_DEVICES'] = "HIP"
cfg_spock.env['KOKKOS_ARCH'] = "Vega908"
cfg_spock.env['CXX'] = 'hipcc'
list_cfg.append(cfg_spock)

cfg_crusher = cfg_spock.get_copy()
cfg_crusher.host_name = 'crusher'
cfg_crusher.env['KOKKOS_ARCH'] = "Vega90A"
list_cfg.append(cfg_crusher)

host_message = "not found, using default settings"
system_settings = cfg_default.env
for cfg in list_cfg:
  if cfg.is_host():
    system_settings = cfg.env
    host_message = "%s (from %s)"%(cfg.host_name, cfg.host_variable)
    break

print("-"*40)
print("         Kokkos configuration\n")
print("     Host: " + host_message)
print("  Devices: " + system_settings['KOKKOS_DEVICES'])
print("     Arch: " + system_settings['KOKKOS_ARCH'])
print("-"*40)

# libkokkos.a
# call kokkos build system directly
# set environment variable defaults if necessary
if os.getenv('KOKKOS_DEVICES') is None:
  os.environ['KOKKOS_DEVICES'] = system_settings['KOKKOS_DEVICES']
if os.getenv('KOKKOS_PATH') is None:
  os.environ['KOKKOS_PATH'] = libtbx.env.under_dist('simtbx', '../../kokkos')
if os.getenv('KOKKOS_ARCH') is None:
  os.environ['KOKKOS_ARCH'] = system_settings['KOKKOS_ARCH']
if os.getenv('KOKKOS_CUDA_OPTIONS') is None:
  os.environ['KOKKOS_CUDA_OPTIONS'] = system_settings['KOKKOS_CUDA_OPTIONS']
os.environ['CXXFLAGS'] = '-O3 -fPIC -DCUDAREAL=double'
os.environ['LDFLAGS'] = system_settings['LDFLAGS']
os.environ['LDLIBS'] = system_settings['LDLIBS']

original_cxx = None
kokkos_lib = 'libkokkos.a'
kokkos_cxxflags = None

if os.getenv('CXX') is not None:
  original_cxx = os.environ['CXX']
if 'Cuda' in os.getenv('KOKKOS_DEVICES'):
  os.environ['CXX'] = os.path.join(os.environ['KOKKOS_PATH'], 'bin', 'nvcc_wrapper')
else:
  os.environ['CXX'] = system_settings['CXX']
print('='*79)
print('Building Kokkos')
print('-'*79)
returncode = subprocess.call(['make', '-f', 'Makefile.kokkos', kokkos_lib],
                              cwd=os.environ['KOKKOS_PATH'])
print()

print('Copying Kokkos library')
print('-'*79)
src = os.path.join(os.environ['KOKKOS_PATH'], kokkos_lib)
dst = os.path.join(libtbx.env.under_build('lib'), kokkos_lib)
if os.path.isfile(src):
  copy(src, dst)
  print('Copied')
  print('  source:     ', src)
  print('  destination:', dst)
else:
  print('Error: {src} does not exist'.format(src=src))
print()

# =============================================================================
# Build kokkos with CMake
# The build needs to be in a directory not in the build directory, otherwise
# kokkos-kernels will find that build directory instead of build/lib/cmake/Kokkos
# The error will look like
#
#   -- The project name is: KokkosKernels
#   CMake Error at /dev/shm/bkpoon/software/xfel/build/kokkos/KokkosConfig.cmake:48 (INCLUDE):
#     INCLUDE could not find requested file:

#       /dev/shm/bkpoon/software/xfel/build/kokkos/KokkosTargets.cmake
#   Call Stack (most recent call first):
#     CMakeLists.txt:107 (FIND_PACKAGE)
#
# kokkos will be installed in build with the libraries in lib, not lib64
#
# TODO:
# - Change over from Makefile version to cmake version
# - Change system configuration classes to select backends with cmake
#   flags instead of environment variables
# - Verify that libraries from cmake version works the same as libkokkos.a

cmake_is_available = which('cmake')
if cmake_is_available:
  print('='*79)
  print('Building kokkos with cmake')
  print('-'*79)
  kokkos_build_dir = libtbx.env.under_dist('simtbx', '../../kokkos_build')
  if not os.path.isdir(kokkos_build_dir):
    os.mkdir(kokkos_build_dir)
  returncode = subprocess.call([
      'cmake',
      os.environ['KOKKOS_PATH'],
      '-DCMAKE_CXX_COMPILER={}'.format(os.environ['CXX']),
      '-DCMAKE_INSTALL_PREFIX={}'.format(libtbx.env.under_build('.')),
      '-DCMAKE_INSTALL_LIBDIR=lib',
      '-DKokkos_ENABLE_SERIAL=ON',
      '-DKokkos_ENABLE_OPENMP=ON'
    ],
    cwd=kokkos_build_dir)
  returncode = subprocess.call(['make', '-j', '4', 'install'], cwd=kokkos_build_dir)

  # -----------------------------------------------------------------------------
  # Build kokkos-kernels with CMake
  print('='*79)
  print('Building kokkos_kernels')
  print('-'*79)
  kokkos_kernels_dir = libtbx.env.under_dist('simtbx', '../../kokkos-kernels')
  returncode = subprocess.call([
      'cmake',
      '.',
      '-DCMAKE_CXX_COMPILER={}'.format(os.environ['CXX']),
      '-DCMAKE_INSTALL_PREFIX={}'.format(libtbx.env.under_build('.')),
      '-DCMAKE_INSTALL_LIBDIR=lib',
      '-DKokkos_ROOT={}'.format(libtbx.env.under_build('.'))
    ],
    cwd=kokkos_kernels_dir)
  returncode = subprocess.call(['make', '-j', '4', 'install'], cwd=kokkos_kernels_dir)
else:
  print('*'*79)
  print('cmake was not found')
  print('Skipping builds of kokkos and kokkos-kernels')
  print('*'*79)
# =============================================================================

print('Getting environment variables')
print('-'*79)
kokkos_cxxflags = subprocess.check_output(
  ['make', '-f', 'Makefile.kokkos', 'print-cxx-flags'],
  cwd=os.environ['KOKKOS_PATH'])
kokkos_cxxflags = kokkos_cxxflags.split(b'\n')
kokkos_cxxflags = kokkos_cxxflags[1].decode('utf8').split()
print('KOKKOS_CXXFLAGS:', kokkos_cxxflags)
print('='*79)

# libsimtbx_kokkos.so
Import("env", "env_etc")

kokkos_env = env.Clone()
kokkos_env.Replace(CXX=os.environ['CXX'])
kokkos_env.Replace(SHCXX=os.environ['CXX'])
kokkos_env.Prepend(CXXFLAGS=['-DCUDAREAL=double'] + kokkos_cxxflags)
kokkos_env.Prepend(CPPFLAGS=['-DCUDAREAL=double'] + kokkos_cxxflags)
kokkos_env.Prepend(CPPPATH=[os.environ['KOKKOS_PATH']])
kokkos_env.Append(LIBS=['kokkos'])

simtbx_kokkos_lib = kokkos_env.SharedLibrary(
  target="#lib/libsimtbx_kokkos.so",
  source=[
    'detector.cpp',
    'kokkos_instance.cpp',
    'kokkos_utils.cpp',
    'simulation.cpp',
    'structure_factors.cpp'
  ]
)

# simtbx_kokkos_ext.so
if not env_etc.no_boost_python:
  Import("env_no_includes_boost_python_ext")
  kokkos_ext_env = env_no_includes_boost_python_ext.Clone()

  env_etc.include_registry.append(
    env=kokkos_ext_env,
    paths=env_etc.simtbx_common_includes + [env_etc.python_include])
  kokkos_ext_env.Replace(CXX=os.environ['CXX'])
  kokkos_ext_env.Replace(SHCXX=os.environ['CXX'])
  kokkos_ext_env.Prepend(CXXFLAGS=['-DCUDAREAL=double'] + kokkos_cxxflags)
  kokkos_ext_env.Prepend(CPPFLAGS=['-DCUDAREAL=double'] + kokkos_cxxflags)
  kokkos_ext_env.Prepend(CPPPATH=[os.environ['KOKKOS_PATH']])
  default_libs = [
    "simtbx_kokkos",
    "scitbx_boost_python",
    env_etc.boost_python_lib,
    "cctbx",
    "kokkos"]
  if 'Cuda' in os.getenv('KOKKOS_DEVICES'):
    kokkos_ext_env.Append(LIBPATH=[os.path.join(os.environ['CUDA_HOME'], 'lib64')])
    kokkos_ext_env.Append(LIBS=env_etc.libm + default_libs + ["cudart", "cuda"])
  elif 'HIP' in os.getenv('KOKKOS_DEVICES'):
    kokkos_ext_env.Append(LIBPATH=[os.path.join(os.environ['ROCM_PATH'], 'lib')])
    kokkos_ext_env.Append(LIBS=env_etc.libm + default_libs + ["amdhip64", "hsa-runtime64"])
  else:
    kokkos_ext_env.Append(LIBS=env_etc.libm + default_libs)

  simtbx_kokkos_ext = kokkos_ext_env.SharedLibrary(
    target="#lib/simtbx_kokkos_ext.so",
    source=['kokkos_ext.cpp']
  )

# reset CXX
if original_cxx is not None:
  os.environ['CXX'] = original_cxx
