"""`to_ssml`'s foreign-name wrapping (`v3/broadcast/live/tts/synth.py`) — what makes a venue's
proper names SOUND like their own language inside another language's narration. The load-bearing
fact (measured 2026-08-11): Google's Studio voices REJECT the `<lang>` tag whole-line and accept
`<phoneme>`, so an entry carrying an IPA transcription must be emitted as a phoneme, and only an
entry without one falls back to `<lang>`. Legacy 2-tuple entries stay byte-identical."""
import sys
from pathlib import Path

import pytest

pytest.importorskip("google.cloud.texttospeech")
_TTS = Path(__file__).resolve().parents[2] / "live" / "tts"
if str(_TTS) not in sys.path:
    sys.path.insert(0, str(_TTS))

from synth import to_ssml  # noqa: E402


def test_a_name_with_ipa_becomes_phoneme_and_one_without_falls_back_to_lang():
    out, is_ssml = to_ssml("en", "We pass Skansen and Red Hats.",
                           [("Skansen", "sv", "ˈskanːsɛn"), ("Red Hats", "sv")])
    assert is_ssml and out.startswith("<speak>")
    assert '<phoneme alphabet="ipa" ph="ˈskanːsɛn">Skansen</phoneme>' in out
    assert '<lang xml:lang="sv">Red Hats</lang>' in out


def test_legacy_two_tuples_and_untouched_lines_render_identically():
    out, is_ssml = to_ssml("en", "Here come the Red Hats.", [("Red Hats", "en-GB")])
    assert is_ssml and '<lang xml:lang="en-GB">Red Hats</lang>' in out
    # a line no rule touches stays PLAIN — same payload, same hash, same clip as before
    assert to_ssml("en", "Nothing to fix here.", [("Skansen", "sv", "x")]) == \
        ("Nothing to fix here.", False)


def test_longest_name_wins_where_entries_overlap():
    out, _ = to_ssml("en", "We cross to Lidingö and the waters of Lidingö Runt.",
                     [("Lidingö", "sv", "ˈliːdɪŋˌøː"), ("Lidingö Runt", "sv", "ˈliːdɪŋˌøː ˈrɵnːt")])
    assert '<phoneme alphabet="ipa" ph="ˈliːdɪŋˌøː ˈrɵnːt">Lidingö Runt</phoneme>' in out
    assert '<phoneme alphabet="ipa" ph="ˈliːdɪŋˌøː">Lidingö</phoneme>' in out
