from __future__ import annotations

from typing import Any

from .exceptions import BrightreeException


class ZeepSoapClient:
    def __init__(self, wsdl: str, username: str, password: str, location: str) -> None:
        try:
            from zeep import Client
            from zeep.transports import Transport
            from requests import Session
            from requests.auth import HTTPBasicAuth
        except ImportError as exc:
            raise BrightreeException(
                "SOAP support requires the optional dependency 'zeep' to be installed.",
                previous=exc,
            ) from exc

        session = Session()
        session.auth = HTTPBasicAuth(username, password)
        transport = Transport(session=session)
        client = Client(wsdl=wsdl, transport=transport)
        binding_name = self._resolve_binding_name(client)
        self._service = client.create_service(binding_name, location)

    def call(self, method: str, params: dict[str, Any]) -> Any:
        operation = getattr(self._service, method)
        return operation(**params)

    @staticmethod
    def _resolve_binding_name(client: Any) -> Any:
        bindings = getattr(getattr(client, "wsdl", None), "bindings", None)
        if not bindings:
            raise BrightreeException("No SOAP bindings were found in the WSDL.")
        return next(iter(bindings))
