#!/usr/bin/env python3
"""Wrapper that exec's the bundled dakota binary inside itis_dakota.

Created by scripts/repair_wheel_macos.sh during wheel repair.
On macOS the dakota binary dynamically links against "Python" (the macOS
framework name). This wrapper:
  1) Locates the real binary bundled inside the itis_dakota package.
  2) Discovers the host Python's shared library via sysconfig.
  3) Creates a directory containing a "Python" symlink that points to the
     real libpython (works for pyenv, Homebrew, python.org framework, etc.).
  4) Injects that directory plus .dylibs/ into DYLD_LIBRARY_PATH.
  5) exec's the real binary.
"""
import os
import sys
import sysconfig
import tempfile


def _find_python_lib():
    """Return path to the Python shared library / framework binary."""
    libdir = sysconfig.get_config_var("LIBDIR") or ""
    ldlib = sysconfig.get_config_var("LDLIBRARY") or ""
    # Framework builds put the binary at e.g.
    # .../Python.framework/Versions/3.12/Python
    # IMPORTANT: use the versioned path (Versions/X.Y/Python), NOT the
    # unversioned /Python.framework/Python symlink, which resolves to
    # Versions/Current and may point to a different Python version.
    fwprefix = sysconfig.get_config_var("PYTHONFRAMEWORKPREFIX") or ""
    fwdir = sysconfig.get_config_var("PYTHONFRAMEWORKDIR") or ""
    if fwprefix and fwdir and fwdir != "no-framework":
        ver = "%d.%d" % (sys.version_info.major, sys.version_info.minor)
        candidate = os.path.join(fwprefix, fwdir, "Versions", ver, "Python")
        if os.path.isfile(candidate):
            return candidate
        # Fallback to unversioned path (single-version installs)
        candidate = os.path.join(fwprefix, fwdir, "Python")
        if os.path.isfile(candidate):
            return candidate
    # Non-framework (pyenv, Homebrew, etc.): libpython3.X.dylib
    candidate = os.path.join(libdir, ldlib)
    if os.path.isfile(candidate):
        return candidate
    return None


def _main():
    import itis_dakota
    pkg_dir = os.path.dirname(os.path.abspath(itis_dakota.__file__))
    binary = os.path.join(pkg_dir, ".bin", "dakota")
    if not os.path.isfile(binary):
        sys.stderr.write(
            "itis_dakota: bundled dakota binary not found at %s\n" % binary
        )
        sys.exit(1)

    # .dylibs/ lives at <site-packages>/.dylibs/
    dylibs_dir = os.path.normpath(os.path.join(pkg_dir, "..", ".dylibs"))

    # The binary links against the bare name "Python". Create a temp
    # directory with a "Python" symlink pointing at the real library so
    # DYLD_LIBRARY_PATH can resolve it.
    python_lib = _find_python_lib()
    extra_paths = []
    if os.path.isdir(dylibs_dir):
        extra_paths.append(dylibs_dir)

    tmpdir = None
    if python_lib:
        # Use a fixed per-user runtime directory to avoid accumulating temp dirs.
        runtime_dir = os.path.join(tempfile.gettempdir(), f"itis_dakota_{os.getuid()}")
        os.makedirs(runtime_dir, exist_ok=True)
        link_path = os.path.join(runtime_dir, "Python")
        # Recreate symlink if target changed (e.g. different Python version).
        if os.path.islink(link_path) and os.readlink(link_path) != python_lib:
            os.unlink(link_path)
        if not os.path.exists(link_path):
            os.symlink(python_lib, link_path)
        extra_paths.insert(0, runtime_dir)

    current = os.environ.get("DYLD_LIBRARY_PATH", "")
    if extra_paths:
        new_val = ":".join(extra_paths)
        if current:
            new_val = new_val + ":" + current
        os.environ["DYLD_LIBRARY_PATH"] = new_val

    os.execv(binary, [binary] + sys.argv[1:])


if __name__ == "__main__":
    _main()
