def map_environment_to_engine(
    environment: "Environment",
    *,
    with_integrations: bool = True,
) -> EnvironmentModel:
    """
    Maps Core API's `environments.models.Environment` model instance to the
    flag_engine environment document.
    Before building the document, takes care of resolving relationships and
    feature versions.

    :param Environment environment: the environment to map
    :rtype EnvironmentModel
    """
    project: "Project" = environment.project
    organisation: "Organisation" = project.organisation

    # Read relationships - grab all the data needed from the ORM here.

    project_segments = [
        ps for ps in project.segments.all() if ps.id == ps.version_of_id
    ]

    project_segment_rules_by_segment_id: Dict[
        int,
        Iterable["SegmentRule"],
    ] = {segment.pk: segment.rules.all() for segment in project_segments}
    project_segment_feature_states_by_segment_id = _get_segment_feature_states(
        project_segments,
        environment.pk,
        latest_environment_feature_version_uuids=(
            {
                efv.uuid
                for efv in EnvironmentFeatureVersion.objects.get_latest_versions_by_environment_id(
                    environment.id
                )
            }
            if environment.use_v2_feature_versioning
            else []
        ),
    )
    environment_feature_states: List["FeatureState"] = _get_prioritised_feature_states(
        [
            feature_state
            for feature_state in environment.feature_states.all()
            if feature_state.feature_segment_id is None
            and feature_state.identity_id is None
        ]
    )
    all_environment_feature_states = (
        *environment_feature_states,
        *chain(*project_segment_feature_states_by_segment_id.values()),
    )
    multivariate_feature_state_values_by_feature_state_id = {
        feature_state.pk: feature_state.multivariate_feature_state_values.all()
        for feature_state in all_environment_feature_states
    }

    # Read integrations.
    integration_configs: dict[
        str, "EnvironmentIntegrationModel | WebhookConfiguration | None"
    ] = {}
    if with_integrations:
        for attr_name in IDENTITY_INTEGRATIONS_RELATION_NAMES:
            integration_config = getattr(environment, attr_name, None)
            if integration_config and not integration_config.deleted:
                integration_configs[attr_name] = integration_config

    # No reading from ORM past this point!

    # Prepare relationships.
    organisation_model = OrganisationModel(
        id=organisation.pk,
        name=organisation.name,
        feature_analytics=organisation.feature_analytics,
        stop_serving_flags=organisation.stop_serving_flags,
        persist_trait_data=organisation.persist_trait_data,
    )
    project_segment_models = [
        SegmentModel(
            id=segment.pk,
            name=segment.name,
            rules=[
                map_segment_rule_to_engine(segment_rule)
                for segment_rule in project_segment_rules_by_segment_id.pop(segment.pk)
            ],
            feature_states=[
                map_feature_state_to_engine(
                    feature_state,
                    mv_fs_values=multivariate_feature_state_values_by_feature_state_id.pop(
                        feature_state.pk,
                    ),
                )
                for feature_state in project_segment_feature_states_by_segment_id.pop(
                    segment.pk
                )
            ],
        )
        for segment in project_segments
    ]
    project_model = ProjectModel(
        id=project.pk,
        name=project.name,
        hide_disabled_flags=project.hide_disabled_flags,
        enable_realtime_updates=project.enable_realtime_updates,
        server_key_only_feature_ids=[
            feature.pk
            for feature_state in environment_feature_states
            if (feature := feature_state.feature).is_server_key_only
        ],
        organisation=organisation_model,
        segments=project_segment_models,
    )
    feature_state_models = [
        map_feature_state_to_engine(
            feature_state,
            mv_fs_values=multivariate_feature_state_values_by_feature_state_id.pop(
                feature_state.pk,
            ),
        )
        for feature_state in environment_feature_states
    ]

    # Prepare integrations.
    amplitude_config_model = map_integration_to_engine(
        integration_configs.pop("amplitude_config", None),
    )
    heap_config_model = map_integration_to_engine(
        integration_configs.pop("heap_config", None),
    )
    mixpanel_config_model = map_integration_to_engine(
        integration_configs.pop("mixpanel_config", None),
    )
    rudderstack_config_model = map_integration_to_engine(
        integration_configs.pop("rudderstack_config", None),
    )
    segment_config_model = map_integration_to_engine(
        integration_configs.pop("segment_config", None),
    )
    webhook_config_model = map_webhook_config_to_engine(
        integration_configs.pop("webhook_config", None),
    )

    return EnvironmentModel(
        #
        # Attributes:
        id=environment.pk,
        api_key=environment.api_key,
        name=environment.name,
        allow_client_traits=environment.allow_client_traits,
        updated_at=environment.updated_at,
        use_identity_composite_key_for_hashing=environment.use_identity_composite_key_for_hashing,
        hide_sensitive_data=environment.hide_sensitive_data,
        hide_disabled_flags=environment.hide_disabled_flags,
        use_identity_overrides_in_local_eval=environment.use_identity_overrides_in_local_eval,
        #
        # Relationships:
        project=project_model,
        feature_states=feature_state_models,
        #
        # Integrations:
        amplitude_config=amplitude_config_model,
        heap_config=heap_config_model,
        mixpanel_config=mixpanel_config_model,
        rudderstack_config=rudderstack_config_model,
        segment_config=segment_config_model,
        webhook_config=webhook_config_model,
    )

    Maps Core API's `environments.models.Environment` model instance to the
    flag_engine environment document.
    Before building the document, takes care of resolving relationships and
    feature versions.

    :param Environment environment: the environment to map
    :rtype EnvironmentModel
    
api/util/mappers/engine.py