"""Allocation-safe parent authority acquisition."""

from __future__ import annotations

import fcntl
import hashlib
import json
import os
import stat
from dataclasses import replace
from pathlib import Path

from .resource_registrar_contract import ResourceRegistrarProtocol
from .weekly_operations_parent import (
    PARENT_SCHEMA,
    WeeklyOperationsParentAuthority,
    WeeklyOperationsParentBinding,
    validate_parent_binding,
)


def _binding(info: os.stat_result) -> WeeklyOperationsParentBinding:
    provisional = WeeklyOperationsParentBinding(
        PARENT_SCHEMA, info.st_dev, info.st_ino, stat.S_IMODE(info.st_mode),
        info.st_uid, info.st_nlink, "",
    )
    payload = {
        field: getattr(provisional, field)
        for field in provisional.__dataclass_fields__
        if field != "binding_digest"
    }
    encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    return replace(
        provisional, binding_digest=hashlib.sha256(encoded).hexdigest()
    )


def acquire_parent_authority_descriptor_owned(
    descriptor: int, acquisition_path: Path, registrar: ResourceRegistrarProtocol
) -> WeeklyOperationsParentAuthority:
    """Acquire a duplicate registered by the caller before this factory returns."""
    owned = registrar.open_fd(lambda: os.dup(descriptor))
    fcntl.flock(owned, fcntl.LOCK_EX)
    try:
        binding = _binding(os.fstat(owned))
        validate_parent_binding(binding)
        return WeeklyOperationsParentAuthority(owned, binding, acquisition_path)
    finally:
        fcntl.flock(owned, fcntl.LOCK_UN)
