"""Resource cleanup utilities for streaming transcription."""

from __future__ import annotations

from typing import TYPE_CHECKING

from noteflow.infrastructure.logging import get_logger

if TYPE_CHECKING:
    from ..protocols import ServicerHost

logger = get_logger(__name__)


def cleanup_stream_resources(host: ServicerHost, meeting_id: str) -> None:
    """Clean up all streaming resources for a meeting.

    Flushes audio buffer and cleans up streaming state.
    This function is idempotent - safe to call multiple times.

    Args:
        host: The servicer host.
        meeting_id: Meeting identifier.
    """
    was_active = meeting_id in host.active_streams

    # Flush audio buffer before cleanup to minimize data loss
    flush_audio_buffer(host, meeting_id)

    # Clean up streaming state
    host.cleanup_streaming_state(meeting_id)

    # Close audio writer
    host.close_audio_writer(meeting_id)

    # Remove from active streams
    host.active_streams.discard(meeting_id)

    if was_active:
        logger.info("Cleaned up stream resources for meeting %s", meeting_id)
    else:
        logger.debug(
            "Cleanup called for meeting %s but was not in active streams (already cleaned up or never initialized)",
            meeting_id,
        )


def flush_audio_buffer(host: ServicerHost, meeting_id: str) -> None:
    """Flush the audio writer buffer for a meeting.

    Args:
        host: The servicer host.
        meeting_id: Meeting identifier.
    """
    if meeting_id not in host.audio_writers:
        return

    try:
        host.audio_writers[meeting_id].flush()
    except (OSError, ValueError) as e:
        logger.warning("Failed to flush audio for %s: %s", meeting_id, e)
