# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.
from __future__ import annotations

from abc import ABC


class BaseSecretsBackend(ABC):
    """Abstract base class to retrieve Connection object given a conn_id or Variable given a key."""

    @staticmethod
    def build_path(path_prefix: str, secret_id: str, sep: str = "/") -> str:
        """
        Given conn_id, build path for Secrets Backend.

        :param path_prefix: Prefix of the path to get secret
        :param secret_id: Secret id
        :param sep: separator used to concatenate connections_prefix and conn_id. Default: "/"
        """
        return f"{path_prefix}{sep}{secret_id}"

    def get_conn_value(self, conn_id: str, team_name: str | None = None) -> str | None:
        """
        Retrieve from Secrets Backend a string value representing the Connection object.

        If the client your secrets backend uses already returns a python dict, you should override
        ``get_connection`` instead.

        :param conn_id: connection id
        :param team_name: Team name associated to the task trying to access the connection (if any)
        """
        raise NotImplementedError

    def get_variable(self, key: str, team_name: str | None = None) -> str | None:
        """
        Return value for Airflow Variable.

        :param key: Variable Key
        :param team_name: Team name associated to the task trying to access the variable (if any)
        :return: Variable Value
        """
        raise NotImplementedError()

    def get_config(self, key: str) -> str | None:
        """
        Return value for Airflow Config Key.

        :param key: Config Key
        :return: Config Value
        """
        return None

    def _set_connection_class(self, conn_class: type) -> None:
        if not isinstance(conn_class, type):
            raise TypeError(f"Connection class must be a type/class, got {type(conn_class).__name__}")
        self._connection_class = conn_class

    def _get_connection_class(self) -> type:
        """Get the Connection class to use for deserialization."""
        conn_class = getattr(self, "_connection_class", None)
        if conn_class is None:
            raise RuntimeError(
                "Connection class not set on backend instance. "
                "Backends must be instantiated via initialize_secrets_backends() "
                "or have _connection_class set manually."
            )
        return conn_class

    @staticmethod
    def _deserialize_connection_value(conn_class: type, conn_id: str, value: str):
        value = value.strip()
        if value[0] == "{":
            return conn_class.from_json(value=value, conn_id=conn_id)  # type: ignore[attr-defined]

        # TODO: Only sdk has from_uri defined on it. Is it worthwhile developing the core path or not?
        if hasattr(conn_class, "from_uri"):
            return conn_class.from_uri(conn_id=conn_id, uri=value)
        return conn_class(conn_id=conn_id, uri=value)

    def deserialize_connection(self, conn_id: str, value: str):
        """
        Given a serialized representation of the airflow Connection, return an instance.

        Uses the Connection class set on this class (which should be set to the appropriate Connection class for the execution context).
        Uses Connection.from_json() for JSON format, Connection(uri=...) for URI format.

        :param conn_id: connection id
        :param value: the serialized representation of the Connection object
        :return: the deserialized Connection
        """
        conn_class = self._get_connection_class()
        return self._deserialize_connection_value(conn_class, conn_id, value)

    def get_connection(self, conn_id: str, team_name: str | None = None):
        """
        Return connection object with a given ``conn_id``.

        :param conn_id: connection id
        :param team_name: Team name associated to the task trying to access the connection (if any)
        :return: Connection object or None
        """
        value = self.get_conn_value(conn_id=conn_id, team_name=team_name)
        if value:
            return self.deserialize_connection(conn_id=conn_id, value=value)
        return None
