import json
import sys
from ansible.plugins.lookup import LookupBase
from ansible.utils.display import Display
display = Display()

# This plugin should only be run after the build is installed.
# This is necessary for zimbot bamboo runs.
sys.path.insert(0, "/opt/zoox/ai/zoox/")
from vehicle.common.config.vehicle_config import get_hardware_config


class LookupModule(LookupBase):
    def run(self, terms, variables=None, **kwargs):
        function = terms.pop(0)
        return [self.__getattribute__(function)(*terms)]

    def get_pepwave_ip_address(self):
        """
        Returns the pepwave's IP, or None if no pepwave is listed in the config.
        Assumes at most one pepwave is present in the config.
        Raises an exception if the pepwave does not have an IP specified.
        """
        config = json.loads(get_hardware_config().toString())
        for ecu in config.get("ecus", []):
            if "pepwave" in ecu:
                return ecu["pepwave"]["ip_addr"]
        return None
