"""Allocation-safe weekly authority-root acquisition."""

from __future__ import annotations

import os

from .resource_registrar_contract import ResourceRegistrarProtocol
from .weekly_operations_authority_root import (
    WeeklyOperationsAuthorityRoot,
    verify_authority_descriptor,
)
from .weekly_operations_parent import (
    WeeklyOperationsAuthorityBinding,
    WeeklyOperationsParentAuthority,
    validate_authority_binding,
)


def open_authority_root_owned(
    parent: WeeklyOperationsParentAuthority,
    binding: WeeklyOperationsAuthorityBinding,
    registrar: ResourceRegistrarProtocol,
) -> WeeklyOperationsAuthorityRoot:
    """Open a root whose duplicate is registered before this factory returns."""
    validate_authority_binding(binding)
    with parent.locked():
        descriptor = registrar.open_fd(lambda: os.dup(parent.descriptor))
        verify_authority_descriptor(descriptor, binding)
        return WeeklyOperationsAuthorityRoot(parent, descriptor, binding)
