import pathlib

import conan
import conan.tools.build
import conan.tools.cmake

class ligo_conan(conan.ConanFile):
  name = "ligo"
  version = "latest"
  description = "C++23 networking and transport library"
  license = "Proprietary"
  package_type = "library"
  settings = "os", "arch", "compiler", "build_type"
  options = {
    "shared": [
      True,
      False,
    ],
    "fPIC": [
      True,
      False,
    ],
    "with_tests": [
      True,
      False,
    ],
  }
  default_options = {
    "shared": False,
    "fPIC": True,
    "with_tests": False,
  }
  python_requires = "modulus/latest"
  exports = "modulus.json"
  exports_sources = (
    "CMakeLists.txt",
    "cmake/*.in",
    "include/*.hpp",
    "include/ligo/*.hpp",
    "include/ligo/detail/*.hpp",
    "src/*.cpp",
    "src/detail/*.cpp",
    "tests/CMakeLists.txt",
    "tests/*.cpp",
    "tests/*.hpp",
  )

  def config_options(self):
    if self.settings.os == "Windows":
      del self.options.fPIC

  def configure(self):
    if self.options.shared:
      del self.options.fPIC

  def requirements(self):
    config = self._modulus_config()
    module = self._modulus_module()
    self.requires(
      str(self.python_requires["modulus"].ref),
      transitive_headers=True,
      transitive_libs=True,
    )
    self.requires(
      module.config.boost_ref(config),
      transitive_headers=True,
      transitive_libs=True,
      options=module.config.boost_requirement_options(config),
    )
    self.requires(
      "openssl/4.0.1",
      transitive_headers=True,
      transitive_libs=True,
    )

  def generate(self):
    deps = conan.tools.cmake.CMakeDeps(self)
    deps.generate()
    toolchain = conan.tools.cmake.CMakeToolchain(self)
    if hasattr(toolchain, "user_presets_path"):
      toolchain.user_presets_path = False
    toolchain.variables["BUILD_SHARED_LIBS"] = bool(self.options.shared)
    toolchain.variables["BUILD_TESTING"] = bool(self.options.with_tests)
    toolchain.generate()

  def build(self):
    cmake = conan.tools.cmake.CMake(self)
    cmake.configure()
    cmake.build()
    if self.options.with_tests and conan.tools.build.can_run(self):
      cmake.test(target="check")

  def package_id(self):
    self.info.options.rm_safe("with_tests")

  def package(self):
    cmake = conan.tools.cmake.CMake(self)
    cmake.install()

  def package_info(self):
    self.cpp_info.set_property(
      "cmake_file_name",
      "ligo",
    )
    self.cpp_info.set_property(
      "cmake_target_name",
      "ligo::ligo",
    )
    self.cpp_info.libs = ["ligo"]

  def _modulus_module(self):
    return self.python_requires["modulus"].module

  def _modulus_config(self):
    return self._modulus_module().config.load_repo_config(pathlib.Path(self.recipe_folder))
