"""Standalone conservative word-level consensus used by Orze-ASR-3Way."""

from __future__ import annotations

from kaldialign import align


EPS = "<eps>"


def _aligned(anchor: list[str], voter: list[str]) -> tuple[list[str], list[list[str]]]:
    values: list[str] = []
    insertions: list[list[str]] = [[]]
    for anchor_word, voter_word in align(anchor, voter, EPS):
        if anchor_word == EPS:
            insertions[-1].append(voter_word)
        else:
            values.append(voter_word)
            insertions.append([])
    if len(values) != len(anchor):
        raise RuntimeError("Alignment did not preserve the anchor word count")
    return values, insertions


def conservative_consensus(anchor_text, voter_one_text, voter_two_text, normalize):
    """Keep anchor words unless both normalized voters agree on an edit."""
    anchor = normalize(anchor_text).split()
    one_values, one_insertions = _aligned(anchor, normalize(voter_one_text).split())
    two_values, two_insertions = _aligned(anchor, normalize(voter_two_text).split())
    output: list[str] = []
    for index, anchor_word in enumerate(anchor):
        if one_insertions[index] and one_insertions[index] == two_insertions[index]:
            output.extend(one_insertions[index])
        voted_word = one_values[index] if one_values[index] == two_values[index] else anchor_word
        if voted_word != EPS:
            output.append(voted_word)
    if one_insertions[-1] and one_insertions[-1] == two_insertions[-1]:
        output.extend(one_insertions[-1])
    return " ".join(output)
