"""Solution for voice_practice.py."""
import statistics

FRAME_MS = 20


def turn_gap(stt, first_sentence, first_audio, wait=0.5):
    if first_audio is None:
        return None
    return wait + stt + first_sentence + first_audio


def summary(gaps, budget=1.0):
    times = [float("inf") if g is None else g for g in gaps]
    return {
        "under": sum(t <= budget for t in times),
        "stalled": sum(g is None for g in gaps),
        "median": statistics.median(times),
        "slowest": max(times),
    }


def hedged(primary, backup, after=1.0):
    if primary is not None and primary <= after:
        return (primary, "primary")
    second = None if backup is None else after + backup
    options = [(t, who) for t, who in ((primary, "primary"), (second, "backup")) if t is not None]
    return min(options) if options else (None, None)


def end_of_turn(is_speech, silence_ms, frame_ms=FRAME_MS):
    need = silence_ms // frame_ms
    heard, quiet = False, 0
    for i, s in enumerate(is_speech):
        if s:
            heard, quiet = True, 0
        elif heard:
            quiet += 1
            if quiet >= need:
                return i
    return None


def words_turn(is_speech, second_start, last, mid_done, end_done, short=500, long=1200):
    first = end_of_turn(is_speech, short if mid_done else long)
    if first is not None and first < second_start:
        return None
    final = end_of_turn(is_speech[second_start:], short if end_done else long) + second_start
    if final < last:
        return None
    return (final - last) * FRAME_MS
