"""Tests from Lab 06. Run: pytest test_tts_practice.py"""
import math

from tts_practice import blame, leading_silence, reading_ok, time_to_first_speech


def test_blame_an_error_both_recognizers_make_on_the_voice():
    b = blame({"quetzals", "negative"}, {"quetzals", "negative"})
    assert b == {"voice": {"quetzals", "negative"}, "recognizer": set()}


def test_blame_a_one_sided_error_on_the_instrument():
    # Nova-3's empty transcript on a clean clip: gpt-transcribe heard it perfectly
    words = {"children", "under", "twelve", "must", "be", "accompanied", "by", "an", "adult"}
    b = blame(words, set())
    assert b == {"voice": set(), "recognizer": words}


def test_reading_matches_an_accepted_form():
    assert reading_ok("Use the password x seven Q nine.", ["use the password x seven q nine"])
    assert reading_ok("The meeting starts at two p.m.", ["the meeting starts at fourteen hundred", "the meeting starts at two pm"])


def test_written_digits_match_spelled_out_digits():
    assert reading_ok("My card ends in 0358", ["my card ends in oh three five eight"])


def test_wrong_readings_are_caught():
    # Real bugs from the lab
    assert not reading_ok("Use the password x seven negative nine quetzals", ["use the password x seven q nine"])
    assert not reading_ok("Only ninety nine today", ["only ninety nine cents today"])
    assert not reading_ok("Email support at dot io", ["email support at acme dot io"])


def test_leading_silence():
    sr = 1000
    audio = [0.0] * 160 + [0.3, -0.4, 0.2]          # 0.16 s of silence, then speech
    assert math.isclose(leading_silence(audio, sr), 0.16)
    assert leading_silence([0.5, 0.1], sr) == 0.0
    assert math.isclose(leading_silence([0.001] * 500, sr), 0.5)


def test_first_byte_is_not_first_word():
    # aura-2-andromeda: 0.33 s to first byte + 0.38 s of silence = 0.71 s to first word
    sr = 1000
    audio = [0.0] * 380 + [0.5]
    assert math.isclose(time_to_first_speech(0.33, audio, sr), 0.71)
