"""Exact descriptor ownership regressions for reminder bootstrap."""

from __future__ import annotations

from pathlib import Path
import sys
import pytest

from gateway.platforms.nutrition_weekly_reminder_bootstrap import (
    WeeklyReminderStartupAuthorityIncident,
)
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,
)


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()
    }


def test_successful_adapter_close_restores_exact_fd_baseline(tmp_path: Path) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    baseline_fds = _fds()
    baseline_bytes = _bytes(tmp_path)
    adapter = TelegramAdapter(config)
    assert len(adapter.weekly_reminder_customers) == 1
    assert _fds() != baseline_fds

    adapter.close_weekly_reminder_capabilities()
    adapter.close_weekly_reminder_capabilities()

    assert adapter.weekly_reminder_customers == ()
    assert _fds() == baseline_fds
    assert _bytes(tmp_path) == baseline_bytes
    fixture.owner.close()


@pytest.mark.parametrize("attempt", (1, 2))
def test_second_customer_failure_closes_every_partial_capability(
    tmp_path: Path, attempt: int
) -> None:
    assert attempt in (1, 2)
    fixture = reminder_owner_fixture(tmp_path, customer_count=2)
    config = platform_config(tmp_path, fixture.extra)
    second_events = (
        tmp_path / "data/customers/client_002/wizard/events.jsonl"
    )
    second_events.chmod(0o640)
    baseline_fds = _fds()
    baseline_bytes = _bytes(tmp_path)

    with pytest.raises(WeeklyReminderStartupAuthorityIncident):
        _ = TelegramAdapter(config)

    assert _fds() == baseline_fds
    assert _bytes(tmp_path) == baseline_bytes
    fixture.owner.close()


def test_owner_construction_failure_closes_transferred_capabilities(
    tmp_path: Path,
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    baseline_fds = _fds()
    adapter = TelegramAdapter(config)
    assert _fds() != baseline_fds

    assert adapter.initialize_nutrition_coaching() is None

    assert adapter.weekly_reminder_customers == ()
    assert _fds() == baseline_fds
    fixture.owner.close()


@pytest.mark.parametrize("interruption", (KeyboardInterrupt, SystemExit))
def test_interruption_after_customer_construction_unwinds_exact_fds(
    tmp_path: Path, interruption: type[BaseException],
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    config = platform_config(tmp_path, fixture.extra)
    baseline_fds = _fds()
    baseline_bytes = _bytes(tmp_path)
    active = [True]

    def interrupt(event: str, arguments: tuple[str]) -> None:
        if (
            active[0]
            and event == "nutricoach.weekly_reminder.customers_constructed"
            and arguments == ("registry.json",)
        ):
            active[0] = False
            raise interruption

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