"""Tests for RefineSpeakerDiarization RPC guards."""

from __future__ import annotations

import grpc
import pytest

from noteflow.grpc._config import ServicesConfig
from noteflow.grpc.proto import noteflow_pb2
from noteflow.grpc.service import NoteFlowServicer
from noteflow.infrastructure.diarization import DiarizationEngine


class _DummyContext:
    """Minimal gRPC context that raises if abort is invoked."""

    async def abort(self, code: grpc.StatusCode, details: str) -> None:
        raise AssertionError(f"abort called: {code} - {details}")

    def set_code(self, code: grpc.StatusCode) -> None:
        """Record response status code (unused in these tests)."""
        return None

    def set_details(self, details: str) -> None:
        """Record response status details (unused in these tests)."""
        return None


class _FakeDiarizationEngine(DiarizationEngine):
    """Lightweight diarization engine stub for service config."""

    def __init__(self) -> None:
        super().__init__()


@pytest.mark.asyncio
async def test_refine_speaker_diarization_rejects_active_meeting() -> None:
    """Refinement should be blocked while a meeting is still recording."""
    servicer = NoteFlowServicer(services=ServicesConfig(diarization_engine=_FakeDiarizationEngine()))
    store = servicer.get_memory_store()

    meeting = store.create("Active meeting")
    meeting.start_recording()
    store.update(meeting)

    response = await servicer.RefineSpeakerDiarization(
        noteflow_pb2.RefineSpeakerDiarizationRequest(meeting_id=str(meeting.id)),
        _DummyContext(),
    )

    assert response.segments_updated == 0, "no segments should be updated for active meeting"
    assert response.error_message, "error message should be present"
    assert "stopped" in response.error_message.lower(), "error should mention 'stopped'"
