import json
from pathlib import Path

from ..dto import JsonPermission, JsonPermissionReference, JsonPermissionRule


def build_json_permission_rule(json_data: dict) -> JsonPermissionRule:
    return JsonPermissionRule(type=json_data["type"], params=json_data["params"])


def build_json_permission_reference(json_data: dict) -> JsonPermissionReference:
    return JsonPermissionReference(type=json_data["type"], field=json_data["field"])


def build_json_permission(json_data: dict) -> JsonPermission:
    return JsonPermission(
        name=json_data["name"],
        rules=[build_json_permission_rule(rule_data) for rule_data in (json_data.get("rules") or [])],
    )


def load_permission(permission_path: str | Path) -> JsonPermission:
    with open(permission_path, "r") as f:
        return build_json_permission(json.load(f))
