"""BaseException proof for every reminder ownership-transfer seam."""

from __future__ import annotations

import sys
from pathlib import Path

import pytest

from gateway.platforms.telegram import TelegramAdapter
from tests.gateway._nutrition_weekly_reminder_support import reminder_owner_fixture
from tests.gateway.test_nutrition_weekly_reminder_bootstrap_boundary_r7 import (
    platform_config,
)

_TRANSFER_HOOKS = (
    "nutricoach.weekly_reminder.last_child_entered_inner_stack",
    "nutricoach.weekly_reminder.owned_container_before_construction",
    "nutricoach.weekly_reminder.owned_container_after_construction",
    "nutricoach.weekly_reminder.owned_container_return_boundary",
    "nutricoach.weekly_reminder.caller_received_before_outer_enter",
    "nutricoach.weekly_reminder.after_outer_enter",
    "nutricoach.weekly_reminder.before_adapter_attribute_assignment",
    "nutricoach.weekly_reminder.after_adapter_attribute_assignment",
    "nutricoach.weekly_reminder.before_outer_pop",
    "nutricoach.weekly_reminder.after_outer_pop",
)


def _fds() -> frozenset[int]:
    return frozenset(
        int(entry.name) for entry in Path("/proc/self/fd").iterdir()
    )


def _bytes(root: Path) -> dict[str, bytes]:
    return {
        str(path.relative_to(root)): path.read_bytes()
        for path in root.rglob("*")
        if path.is_file()
    }


@pytest.mark.parametrize("hook", _TRANSFER_HOOKS)
@pytest.mark.parametrize("interruption", (KeyboardInterrupt, SystemExit))
@pytest.mark.parametrize("attempt", (1, 2))
def test_every_transfer_seam_unwinds_without_one_fd_leak(
    tmp_path: Path,
    hook: str,
    interruption: type[BaseException],
    attempt: int,
) -> None:
    assert attempt in (1, 2)
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    baseline_fds = _fds()
    baseline_bytes = _bytes(tmp_path)
    active = [True]
    created: list[TelegramAdapter] = []

    def interrupt(event: str, _arguments: tuple[str]) -> None:
        if active[0] and event == hook:
            active[0] = False
            raise interruption

    sys.addaudithook(interrupt)
    try:
        with pytest.raises(interruption):
            created.append(TelegramAdapter(config))
        assert not active[0]
        assert created == []
        assert _fds() == baseline_fds
        assert len(_fds()) == len(baseline_fds)
        assert _bytes(tmp_path) == baseline_bytes
    finally:
        active[0] = False
        fixture.owner.close()
