"""Mutation-free production bootstrap for weekly reminder capabilities."""

from __future__ import annotations

import os
import stat
import sys
from typing import TYPE_CHECKING

from gateway.platforms.nutrition_weekly_operations_config import (
    WeeklyOperationsAuthorityError,
    WeeklyOperationsConfigError,
)
from gateway.platforms.nutrition_weekly_reminder_bootstrap_config import (
    BootstrapConfigIncident,
    OperatorAuthoritySnapshot,
    OwnedWeeklyReminderCustomers,
    WeeklyReminderStartupAuthorityIncident,
    capture_operator_authority,
    new_owned_weekly_reminder_customers,
    mapping,
    profile_root,
    relative_name,
)
from gateway.platforms.nutrition_weekly_operations_registry_identity import (
    PinnedProfileRegistry,
    open_pinned_profile_registry,
    open_relative,
)

__all__ = (
    "WeeklyReminderStartupAuthorityIncident",
    "load_registered_weekly_reminder_customers",
)

if TYPE_CHECKING:
    from gateway.config import PlatformConfig


def _verify_authority_directory(descriptor: int) -> tuple[int, int]:
    info = os.fstat(descriptor)
    if (
        not stat.S_ISDIR(info.st_mode)
        or stat.S_IMODE(info.st_mode) != 0o700
        or info.st_uid != os.geteuid()
        or info.st_nlink != 2
    ):
        raise WeeklyReminderStartupAuthorityIncident(
            "weekly reminder sidecar authority identity is unsafe"
        )
    return info.st_dev, info.st_ino


def _verify_authority_attachment(
    pinned: PinnedProfileRegistry, relative: str, descriptor: int,
    ownership: OwnedWeeklyReminderCustomers,
) -> None:
    retained = _verify_authority_directory(descriptor)
    named = open_relative(
        pinned.root_fd, relative, directory=True, registrar=ownership.registrar
    )
    try:
        if retained != _verify_authority_directory(named):
            raise WeeklyReminderStartupAuthorityIncident(
                "weekly reminder sidecar authority attachment drift"
            )
    finally:
        ownership.registrar.close_fd(named)


def _load_enabled(
    config: PlatformConfig,
    snapshot: OperatorAuthoritySnapshot,
) -> OwnedWeeklyReminderCustomers:
    from checkin_cli.weekly_operations import WeeklyOperationsError
    from gateway.platforms.nutrition_weekly_reminder_bootstrap_customers import (
        construct_owned_customers,
    )

    try:
        snapshot.verify(config)
        nutrition = mapping(config.extra.get("nutrition_coaching"))
        receipt = snapshot.receipt
        weekly = snapshot.weekly
        if (
            weekly.registry_identity_binding_digest
            != receipt.registry_identity.binding_digest
        ):
            raise WeeklyReminderStartupAuthorityIncident(
                "weekly reminder config registry authority disagrees"
            )
        configured_registry = relative_name(
            nutrition.get("registry_path"), "registry path"
        )
        if configured_registry != receipt.registry_identity.relative_name:
            raise WeeklyReminderStartupAuthorityIncident(
                "weekly reminder configured registry authority disagrees"
            )
        authority_name = relative_name(
            nutrition.get("weekly_operations_authority_path", "weekly-authority"),
            "sidecar authority path",
        )
        ownership = new_owned_weekly_reminder_customers()
        with ownership.close_on_error():
            pinned = open_pinned_profile_registry(
                profile_root(config), receipt.registry_identity, ownership.registrar
            )
            sys.audit(
                "nutricoach.weekly_reminder.registry_pinned",
                receipt.registry_identity.relative_name,
            )
            authority_fd = open_relative(
                pinned.root_fd, authority_name, directory=True,
                registrar=ownership.registrar,
            )
            _ = _verify_authority_directory(authority_fd)
            sys.audit("nutricoach.weekly_reminder.authority_fd_registered")
            construct_owned_customers(
                ownership,
                ownership.registrar,
                pinned,
                authority_name,
                authority_fd,
                receipt.registry_identity,
                receipt.enabled_customer_keys,
                receipt.consent_digest,
            )
            sys.audit(
                "nutricoach.weekly_reminder.customers_constructed",
                receipt.registry_identity.relative_name,
            )
            snapshot.verify(config)
            pinned.verify_registered(ownership.registrar)
            _verify_authority_attachment(
                pinned, authority_name, authority_fd, ownership
            )
            return ownership
    except BootstrapConfigIncident as error:
        raise WeeklyReminderStartupAuthorityIncident(str(error)) from error
    except WeeklyReminderStartupAuthorityIncident:
        raise
    except (
        OSError, ValueError, WeeklyOperationsAuthorityError, WeeklyOperationsError
    ) as error:
        raise WeeklyReminderStartupAuthorityIncident(
            "weekly reminder startup authority is unavailable"
        ) from error


def load_registered_weekly_reminder_customers(
    config: PlatformConfig,
) -> OwnedWeeklyReminderCustomers:
    """Consume one immutable operator input and transfer existing capabilities."""
    try:
        snapshot = capture_operator_authority(config)
    except (
        BootstrapConfigIncident,
        WeeklyOperationsAuthorityError,
        WeeklyOperationsConfigError,
    ) as error:
        raise WeeklyReminderStartupAuthorityIncident(
            "weekly reminder startup config is invalid"
        ) from error
    if snapshot is None:
        return new_owned_weekly_reminder_customers()
    return _load_enabled(config, snapshot)
