"""Test-only acquisition helpers for the parent authority capability."""

from __future__ import annotations

from pathlib import Path

from checkin_cli.weekly_operations_authority import AuthorityId, WeeklyOperationsAuthorityRoot, begin_authority_initialization
from checkin_cli.weekly_operations_parent import WeeklyOperationsParentAuthority, acquire_parent_authority


def acquire_for_child(path: Path) -> WeeklyOperationsParentAuthority:
    if not path.exists():
        path.mkdir(parents=True, mode=0o700)
    path.chmod(0o700)
    return acquire_parent_authority(path)


def initialize_for_parent(parent: WeeklyOperationsParentAuthority, authority_id: AuthorityId) -> WeeklyOperationsAuthorityRoot:
    authority: WeeklyOperationsAuthorityRoot | None = None
    with begin_authority_initialization(parent, authority_id) as transaction:
        authority = transaction.authority
        _ = transaction.binding
        transaction.acknowledge_binding()
    if authority is None:
        raise AssertionError("acknowledged initialization did not expose authority")
    return authority


def initialize_at(path: Path, authority_id: AuthorityId) -> WeeklyOperationsAuthorityRoot:
    return initialize_for_parent(acquire_for_child(path), authority_id)
