from pathlib import Path

from edpauthorization.dto import AuthorizationPrincipal, AuthorizationRequest
from edpauthorization.exception import PolicyNotFoundException, MissingPrincipalException
from edpauthorization.service import AuthorizationService

from .builder import load_permission
from .verification import verify_permission


class JsonAuthorizationServiceImpl(AuthorizationService):
    def __init__(self, permission_dir: str):
        self.permission_dir = permission_dir

    def _permission_path(self, resource_type: str, action_name: str) -> Path:
        return Path(self.permission_dir, resource_type, f"{action_name}.json")

    def _is_authorized(self, principal: AuthorizationPrincipal, request: AuthorizationRequest) -> bool:
        if principal is None:
            raise MissingPrincipalException()
        resource_type = request["resource_type"]
        action_name = request["action_name"]

        permission_path = self._permission_path(
            resource_type=resource_type,
            action_name=action_name,
        )

        if not permission_path.exists() or not permission_path.is_file():
            raise PolicyNotFoundException(f"Policy for resource {resource_type} and action {action_name} not found")

        permission = load_permission(permission_path)
        return verify_permission(permission=permission, parameters={"principal": principal, **request})
