"""Speaker assignment utilities for mapping diarization to segments.

Provides functions to assign speaker labels to transcript segments based on
diarization output using timestamp overlap matching.
"""

from collections.abc import Sequence

from noteflow.infrastructure.diarization.dto import SpeakerTurn


def assign_speaker(
    start_time: float,
    end_time: float,
    turns: Sequence[SpeakerTurn],
) -> tuple[str | None, float]:
    """Assign a speaker to a time range based on diarization turns.

    Uses maximum overlap duration to determine the dominant speaker
    for the given time range.

    Args:
        start_time: Segment start time in seconds.
        end_time: Segment end time in seconds.
        turns: Sequence of speaker turns from diarization.

    Returns:
        Tuple of (speaker_id, confidence) where speaker_id is None if
        no overlapping turns found. Confidence is the ratio of overlap
        duration to segment duration.
    """
    if not turns:
        return None, 0.0

    segment_duration = end_time - start_time
    if segment_duration <= 0:
        return None, 0.0

    best_speaker: str | None = None
    best_overlap: float = 0.0

    for turn in turns:
        overlap = turn.overlap_duration(start_time, end_time)
        if overlap > best_overlap:
            best_overlap = overlap
            best_speaker = turn.speaker

    if best_speaker is None:
        return None, 0.0

    confidence = best_overlap / segment_duration
    return best_speaker, confidence


def assign_speakers_batch(
    segments: Sequence[tuple[float, float]],
    turns: Sequence[SpeakerTurn],
) -> list[tuple[str | None, float]]:
    """Assign speakers to multiple segments in batch.

    Args:
        segments: Sequence of (start_time, end_time) tuples.
        turns: Sequence of speaker turns from diarization.

    Returns:
        List of (speaker_id, confidence) tuples, one per segment.
    """
    return [assign_speaker(start, end, turns) for start, end in segments]
