from __future__ import annotations

import pytest

from terminaluse.lib.core.services.adk.acp.acp import ACPService
from terminaluse.types import TextPart


class _NoopSpan:
    async def __aenter__(self):
        return None

    async def __aexit__(self, exc_type, exc, tb):
        return False


class _NoopTrace:
    def span(self, **kwargs):
        _ = kwargs
        return _NoopSpan()


class _NoopTracer:
    def trace(self, *_args, **_kwargs):
        return _NoopTrace()


class _FakeEvent:
    def model_dump(self):
        return {"id": "evt_1"}


class _CapturingTasksClient:
    def __init__(self):
        self.calls: list[dict] = []

    async def send_event(self, **kwargs):
        self.calls.append(kwargs)
        return _FakeEvent()


class _CapturingTerminalUseClient:
    def __init__(self, tasks_client: _CapturingTasksClient):
        self.tasks = tasks_client


@pytest.mark.asyncio
async def test_event_send_sets_idempotency_key_and_preserves_headers():
    tasks_client = _CapturingTasksClient()
    service = ACPService(
        terminaluse_client=_CapturingTerminalUseClient(tasks_client),  # type: ignore[arg-type]
        tracer=_NoopTracer(),  # type: ignore[arg-type]
    )

    await service.event_send(
        task_id="task_1",
        content=TextPart(text="hello"),
        request={"headers": {"x-test": "1"}},
    )

    assert len(tasks_client.calls) == 1
    call = tasks_client.calls[0]
    assert isinstance(call["idempotency_key"], str)
    assert call["idempotency_key"] != ""
    request_options = call["request_options"]
    assert request_options["additional_headers"] == {"x-test": "1"}
