% Auto-detect libffi include path on each platform.
% On macOS, ffi.h lives inside the Xcode/CLT SDK under usr/include/ffi/.
% On Linux, pkg-config or the hard-coded fallback in rebar.config already covers it.

DarwinFFIInclude =
    case os:type() of
        {unix, darwin} ->
            Candidates = [
                %% Homebrew (arm64 / x86_64)
                "/opt/homebrew/opt/libffi/include",
                "/usr/local/opt/libffi/include",
                %% Xcode CommandLineTools SDK
                string:trim(os:cmd("xcrun --show-sdk-path 2>/dev/null")) ++
                    "/usr/include/ffi"
            ],
            lists:foldl(fun
                (_, Acc) when Acc =/= "" -> Acc;
                (Dir, _) ->
                    case filelib:is_dir(Dir) of
                        true  -> " -I" ++ Dir;
                        false -> ""
                    end
            end, "", Candidates);
        _ ->
            ""
    end,

PortEnv = proplists:get_value(port_env, CONFIG, []),
NewPortEnv = lists:map(fun
    ({"darwin", "CFLAGS", Val}) -> {"darwin", "CFLAGS", Val ++ DarwinFFIInclude};
    (Other) -> Other
end, PortEnv),

lists:keyreplace(port_env, 1, CONFIG, {port_env, NewPortEnv}).
