import logging
import os
from typing import Any

from edpauthorization.service import AuthorizationService

_DEFAULT_LOGGER = logging.getLogger("edpauthorization.builder")

_AUTHORIZATION_ENV = "EDP_AUTHORIZATION_SERVICE"


def _parse_bool(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    if isinstance(value, str):
        return value.lower() in ("true", "1", "yes")
    return bool(value)


def _get_args(args: dict, field: str, env_variable: str | None = None, default_value: Any | None = None) -> str | None:
    if field in args:
        return args[field]

    if env_variable is None:
        env_variable = f"{_AUTHORIZATION_ENV}_{field.upper()}"
    if env_variable in os.environ:
        return os.environ[env_variable]
    return default_value


def build_service(**kwargs) -> AuthorizationService:
    authorization_service = _get_args(
        kwargs,
        field="service_name",
        env_variable=_AUTHORIZATION_ENV,
        default_value="off",
    )
    _DEFAULT_LOGGER.debug("Loading service: %s", authorization_service)

    if authorization_service == "awsverifiedpermissions":
        from ..service.impl.cedar.aws import VerifiedPermissionsAuthorizationServiceImpl

        return VerifiedPermissionsAuthorizationServiceImpl(
            policy_store_id=_get_args(kwargs, "policy_store_id"),
            schema_namespace=_get_args(kwargs, "schema_namespace"),
            use_batch=_parse_bool(_get_args(kwargs, "use_batch")),
        )
    if authorization_service == "cedarpy":
        from ..service.impl.cedar.cedarpy import CedarpyAuthorizationServiceImpl

        return CedarpyAuthorizationServiceImpl(
            permission_dir=_get_args(kwargs, "dir"),
            schema_namespace=_get_args(kwargs, "schema_namespace"),
        )
    if authorization_service == "cedarapi":
        from ..service.impl.cedar.cedarapi import CedarApiAuthorizationServiceImpl

        return CedarApiAuthorizationServiceImpl(
            cedar_service_url=_get_args(kwargs, "url"),
            schema_namespace=_get_args(kwargs, "schema_namespace"),
            use_batch=_parse_bool(_get_args(kwargs, "use_batch")),
        )
    elif authorization_service == "json":
        import warnings

        from ..service.impl.json import JsonAuthorizationServiceImpl

        warnings.warn(
            "The 'json' authorization backend is deprecated and will be removed in a future version. "
            "Use 'cedarpy' or 'awsverifiedpermissions' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return JsonAuthorizationServiceImpl(
            permission_dir=_get_args(kwargs, "dir"),
        )
    else:
        from ..service.impl.noauthorization import NoAuthorizationServiceImpl

        return NoAuthorizationServiceImpl()
