"""Behavioral delegation proof for all inherited Todo11 Telegram seams."""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import override

import pytest

from gateway.platforms.nutrition_coaching import (
    IncomingAddress,
    NutritionCoachingCoordinator,
)
from gateway.platforms.nutrition_draft_callback_route import (
    NutritionDraftCallbackDenied,
    NutritionDraftCallbackDenialReason,
)
from gateway.platforms.nutrition_weekly_dispatcher import (
    WeeklyOperationsCoordinator,
    WeeklyOperationsTask,
)
from gateway.platforms.nutrition_weekly_operations_publication_contract import (
    Topic59ProviderDelivered,
)
from gateway.platforms.telegram_edit_transport import (
    TelegramEditDelivered,
    TelegramEditOutcome,
)
from scripts.nutricoach_v140_authority_fixture import CANDIDATE
from scripts.nutricoach_v140_fake_telegram import FakeTelegramEngine, fake_bot
from scripts.nutricoach_v140_fake_telegram_updates import (
    FakeCallbackQuery,
    FakeChat,
    FakeMessage,
)
from scripts.nutricoach_v140_owner_fixture import (
    create_owner_coordinator,
    owner_platform_config,
)
from scripts.nutricoach_v140_telegram_facade import (
    DisposableOwnerTelegramAdapter,
    DisposableWeeklyTelegramAdapter,
)
from scripts.nutricoach_v140_tick_fixture import (
    create_tick_fixture,
    reminder_time,
)


@dataclass(frozen=True, slots=True)
class _ProviderMessage:
    message_id: int


class _WeeklyFacadeSpy(DisposableWeeklyTelegramAdapter):
    tick_calls: int = 0
    send_calls: int = 0
    edit_calls: int = 0

    @override
    async def _tick_handler_seam(
        self,
        coordinator: WeeklyOperationsCoordinator,
        tasks: Sequence[WeeklyOperationsTask],
        now: datetime,
    ) -> tuple[str, ...]:
        _ = coordinator, tasks, now
        self.tick_calls += 1
        return ("tick-spy",)

    @override
    async def _send_handler_seam(
        self, chat_id: str, topic_id: str, text: str,
    ) -> _ProviderMessage:
        _ = chat_id, topic_id, text
        self.send_calls += 1
        return _ProviderMessage(777)

    @override
    async def _edit_handler_seam(
        self, chat_id: str, message_id: str, text: str,
    ) -> TelegramEditOutcome:
        _ = chat_id, message_id, text
        self.edit_calls += 1
        return TelegramEditDelivered("888")


class _OwnerFacadeSpy(DisposableOwnerTelegramAdapter):
    callback_calls: int = 0
    text_calls: int = 0

    @override
    async def _callback_handler_seam(
        self, query: FakeCallbackQuery,
    ) -> NutritionDraftCallbackDenied | None:
        _ = query
        self.callback_calls += 1
        return NutritionDraftCallbackDenied(
            NutritionDraftCallbackDenialReason.WRONG_USER,
        )

    @override
    async def _text_handler_seam(
        self,
        message: FakeMessage,
        owner: IncomingAddress,
        coordinator: NutritionCoachingCoordinator,
    ) -> bool:
        _ = message, owner, coordinator
        self.text_calls += 1
        return True


@pytest.fixture
def anyio_backend() -> str:
    return "asyncio"


@pytest.mark.anyio
async def test_public_facades_delegate_all_inherited_seams(tmp_path: Path) -> None:
    fixture, coordinator, config, reminder, _ = create_tick_fixture(tmp_path / "tick")
    weekly = _WeeklyFacadeSpy(config, fake_bot(FakeTelegramEngine()), CANDIDATE)
    tick = await weekly.run_weekly_tick(coordinator, (reminder,), reminder_time())
    sent = await weekly.send_topic59("200", "59", "safe")
    edited = await weekly.edit_topic59("200", "59", "777", "later")
    assert fixture.store.read() == () and tick == ("tick-spy",)
    assert isinstance(sent, Topic59ProviderDelivered) and sent.message_id == "777"
    assert isinstance(edited, Topic59ProviderDelivered) and edited.message_id == "888"
    assert (weekly.tick_calls, weekly.send_calls, weekly.edit_calls) == (1, 1, 1)

    coordinator_owner = create_owner_coordinator(tmp_path / "owner")
    engine = FakeTelegramEngine()
    bot = fake_bot(engine)
    _ = await bot.send_message(chat_id=100, text="safe")
    owner = _OwnerFacadeSpy(owner_platform_config(), bot, coordinator_owner)
    message = FakeMessage("100", 100, None, FakeChat("100", "private"), "safe")
    query = FakeCallbackQuery(
        bot, engine, data="invalid", user_id="100", chat_id="100",
        message_id="100", topic_id=None,
    )
    denial = await owner.handle_owner_callback(query)
    handled = await owner.handle_owner_text(
        message, IncomingAddress("100", "100", "0"), coordinator_owner,
    )
    assert denial == NutritionDraftCallbackDenied(
        NutritionDraftCallbackDenialReason.WRONG_USER,
    )
    assert handled is True
    assert (owner.callback_calls, owner.text_calls) == (1, 1)