"""Shared helpers for chat stream tests."""

from __future__ import annotations

import asyncio

from app.models.chat import ChatCompletionChunk, Choice, DeltaContent


def _failed_report_tasks_snapshot() -> list:
    from app.api import chat as chat_mod

    return list(chat_mod._failed_report_tasks)


class ChatStreamCase:
    def _run_async(self, gen):
        loop = asyncio.new_event_loop()
        try:
            results = []
            while True:
                try:
                    results.append(loop.run_until_complete(gen.__anext__()))
                except StopAsyncIteration:
                    break
            return results
        finally:
            loop.close()

    def _run_stream(self, gen):
        """Drain a stream and its report tasks in the same event loop."""
        loop = asyncio.new_event_loop()
        try:
            results = []
            while True:
                try:
                    results.append(loop.run_until_complete(gen.__anext__()))
                except StopAsyncIteration:
                    break
            tasks = _failed_report_tasks_snapshot()
            if tasks:
                loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
            return results
        finally:
            loop.close()

    def _build_sse_chunk(
        self, content: str, finish_reason: str | None = None, system_notice: bool | None = None
    ) -> str:
        chunk = ChatCompletionChunk(
            id="chatcmpl-test",
            created=0,
            model="test-model",
            choices=[
                Choice(
                    delta=DeltaContent(role="assistant", content=content),
                    finish_reason=finish_reason,
                    system_notice=system_notice,
                )
            ],
        )
        return f"data: {chunk.model_dump_json(exclude_none=True)}\n\n"

    def _clear_pending_registry(self):
        from app.services import eval_client as ec

        with ec._pending_evaluations_lock:
            ec._pending_evaluations.clear()

    def _sse_with_flags(self, content: str, **flags) -> str:
        chunk = ChatCompletionChunk(
            id="chatcmpl-test",
            created=0,
            model="test-model",
            choices=[Choice(delta=DeltaContent(role="assistant", content=content), **flags)],
        )
        return f"data: {chunk.model_dump_json(exclude_none=True)}\n\n"