"""Exception-safe ownership for constructed weekly reminder customers."""

from __future__ import annotations

import os
import sys
from contextlib import ExitStack

from checkin_cli.customer_coaching import load_customer_registry_bytes
from checkin_cli.weekly_operations import CustomerKey
from checkin_cli.weekly_operations_authority import (
    AuthorityId,
    construct_authority_binding,
)
from checkin_cli.weekly_operations_authority_owned import open_authority_root_owned
from checkin_cli.weekly_operations_canonical_registry import locked_registration_history
from checkin_cli.weekly_operations_canonical_registry_history import REGISTRY_NAME
from checkin_cli.weekly_operations_customer_authority_owned import (
    acquire_unregistered_authority_owned,
)
from checkin_cli.weekly_operations_parent import (
    read_authority_marker,
)
from checkin_cli.weekly_operations_parent_owned import (
    acquire_parent_authority_descriptor_owned,
)
from checkin_cli.weekly_operations_registered_binding import create_registered_binding
from checkin_cli.weekly_operations_store import WeeklyOperationsStore
from checkin_cli.weekly_reminder_ledger_open_owned import (
    open_registered_weekly_reminder_ledger_authority_owned,
)

from .nutrition_weekly_operations_registry_identity import (
    PinnedProfileRegistry,
    WeeklyOperationsRegistryIdentity,
)
from .nutrition_weekly_reminder_authority import RegisteredWeeklyReminderCustomer
from .nutrition_weekly_reminder_owner_factory import weekly_reminder_consent_digest
from .nutrition_weekly_reminder_resources import ResourceRegistrar
from .nutrition_weekly_reminder_bootstrap_config import (
    OwnedWeeklyReminderCustomers,
    WeeklyReminderStartupAuthorityIncident,
)


def _directory_identity(descriptor: int) -> tuple[int, int]:
    info = os.fstat(descriptor)
    return info.st_dev, info.st_ino


def construct_owned_customers(
    owned: OwnedWeeklyReminderCustomers,
    registrar: ResourceRegistrar,
    pinned: PinnedProfileRegistry,
    authority_name: str,
    authority_fd: int,
    receipt_identity: WeeklyOperationsRegistryIdentity,
    enabled_customer_keys: tuple[str, ...],
    consent_digest: str,
) -> None:
    with owned.close_on_error():
        if pinned.identity != receipt_identity:
            raise WeeklyReminderStartupAuthorityIncident(
                "weekly reminder registry authority disagrees"
            )
        registry = load_customer_registry_bytes(pinned.payload, pinned.root_path)
        parent = acquire_parent_authority_descriptor_owned(
            authority_fd, pinned.root_path / authority_name, registrar
        )
        sys.audit("nutricoach.weekly_reminder.parent_registered")
        if _directory_identity(parent.descriptor) != _directory_identity(authority_fd):
            raise WeeklyReminderStartupAuthorityIncident(
                "weekly reminder sidecar authority descriptor drift"
            )
        marker, marker_digest, marker_info = read_authority_marker(parent.descriptor)
        sidecar_registry = os.stat(
            REGISTRY_NAME, dir_fd=parent.descriptor, follow_symlinks=False
        )
        binding = construct_authority_binding(
            AuthorityId(marker.authority_id),
            os.fstat(parent.descriptor),
            marker_info,
            marker_digest,
            sidecar_registry,
            marker.registry_digest,
        )
        authority = open_authority_root_owned(
            parent, binding, registrar
        )
        sys.audit("nutricoach.weekly_reminder.weekly_authority_registered")
        with locked_registration_history(authority, exclusive=False) as locked:
            _descriptor, rows = locked
        by_customer = {row.customer_identity_digest: row for row in rows}
        by_key = {runtime.spec.customer_key: runtime for runtime in registry.customers}
        if set(by_key) != set(enabled_customer_keys):
            raise WeeklyReminderStartupAuthorityIncident(
                "weekly reminder enabled customer registry disagrees"
            )
        last_index = len(enabled_customer_keys) - 1
        for index, key in enumerate(enabled_customer_keys):
            runtime = by_key[key]
            source = acquire_unregistered_authority_owned(
                runtime, authority, registrar
            )
            sys.audit("nutricoach.weekly_reminder.source_registered")
            row = by_customer.get(source.customer_identity_digest)
            if row is None or row.binding_digest != source.binding_digest:
                raise WeeklyReminderStartupAuthorityIncident(
                    "weekly reminder canonical registration is unavailable"
                )
            registered = create_registered_binding(
                source.binding,
                row.row_digest,
                row.authority_binding_digest,
                row.authority_marker_digest,
                row.registry_binding_digest,
            )
            source.attach_registered_binding(registered)
            source.verify()
            if weekly_reminder_consent_digest(runtime) != consent_digest:
                raise WeeklyReminderStartupAuthorityIncident(
                    "weekly reminder consent authority disagrees"
                )
            store = WeeklyOperationsStore.for_authority(authority, CustomerKey(key))
            ledger = open_registered_weekly_reminder_ledger_authority_owned(
                source, store, registrar
            )
            sys.audit("nutricoach.weekly_reminder.ledger_registered")
            if index == last_index:
                sys.audit(
                    "nutricoach.weekly_reminder.last_child_entered_inner_stack"
                )
            customer = RegisteredWeeklyReminderCustomer(
                runtime, source, store, ledger, ExitStack()
            )
            owned.add_customer(customer)
        sys.audit("nutricoach.weekly_reminder.owned_container_return_boundary")
        return None
