# Copyright (c) 2026 Thomas Goirand <zigo@debian.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from oslo_log import log as logging

LOG = logging.getLogger(__name__)


def get_nova_compute_service(conn, host):
    """
    Fetch nova-compute service(s) for a given host.
    
    This function handles both newer and older OpenStack SDK versions.
    Newer SDKs support filtering by binary and host parameters directly,
    while older SDKs require manual filtering.
    
    Args:
        conn (openstack.connection.Connection): OpenStack SDK connection object
        host (str): The hostname of the compute node
        
    Returns:
        list: List of nova-compute service objects matching the host (may be empty)
    """
    LOG.debug(f"Fetching nova-compute service for '{host}'.")
    try:
        # List all services and filter the one that matches
        # the given host and binary
        services = list(conn.compute.services(binary='nova-compute',
                                              host=host))
    except TypeError:
        LOG.debug("Old SDK detected — manually filtering services.")
        # Older OpenStack SDK do not have binary and host
        # parameters, so we need to do the filtering by
        # ourself.
        all_services = list(conn.compute.services())
        services = [
            svc for svc in all_services
            if svc.binary == 'nova-compute' and svc.host == host
        ]

    return services
