"""
Tests for legacy unified terminal deduplication mode.

Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com
"""

from __future__ import annotations

from typing import Any, Generator, List

import pytest

from mcp_proxy_adapter.core.job_push.notifier import (
    NotificationDomain,
    clear_notifier_listeners,
    configure_notifier_job_push_policy,
    notify_job_state_changed,
    register_notifier_listener,
)


@pytest.fixture(autouse=True)
def reset_notifier_state() -> Generator[None, None, None]:
    """Reset notifier state before and after each test."""
    clear_notifier_listeners()
    configure_notifier_job_push_policy(legacy_unified_terminal_dedup=False)
    yield
    clear_notifier_listeners()
    configure_notifier_job_push_policy(legacy_unified_terminal_dedup=False)


@pytest.mark.asyncio
async def test_legacy_dedup_off_cross_domain_not_suppressed() -> None:
    """Test that with legacy dedup off, cross-domain terminal notifications are not suppressed."""
    calls: List[tuple[NotificationDomain, str, str]] = []

    def capture_listener(
        domain: NotificationDomain,
        identifier: str,
        status: str,
        result: Any,
        error: Any,
        progress: int,
        description: str,
    ) -> None:
        calls.append((domain, identifier, status))

    register_notifier_listener(capture_listener)
    configure_notifier_job_push_policy(legacy_unified_terminal_dedup=False)

    await notify_job_state_changed(
        NotificationDomain.QUEUE_JOB, "X", "completed", result={}
    )
    await notify_job_state_changed(
        NotificationDomain.WS_DELIVERY, "X", "completed", result={}
    )

    assert len(calls) == 2
    assert calls[0] == (NotificationDomain.QUEUE_JOB, "X", "completed")
    assert calls[1] == (NotificationDomain.WS_DELIVERY, "X", "completed")


@pytest.mark.asyncio
async def test_legacy_dedup_on_cross_domain_terminal_suppressed() -> None:
    """Test that with legacy dedup on, cross-domain terminal notifications are suppressed."""
    calls: List[tuple[NotificationDomain, str, str]] = []

    def capture_listener(
        domain: NotificationDomain,
        identifier: str,
        status: str,
        result: Any,
        error: Any,
        progress: int,
        description: str,
    ) -> None:
        calls.append((domain, identifier, status))

    register_notifier_listener(capture_listener)
    configure_notifier_job_push_policy(legacy_unified_terminal_dedup=True)

    await notify_job_state_changed(
        NotificationDomain.QUEUE_JOB, "X", "completed", result={}
    )
    await notify_job_state_changed(
        NotificationDomain.WS_DELIVERY, "X", "completed", result={}
    )

    assert len(calls) == 1
    assert calls[0] == (NotificationDomain.QUEUE_JOB, "X", "completed")
