from browser import document
import re
import difflib


def to_word_stream(text: str) -> str:
    """Normalize text to lowercase words separated by single spaces."""
    letters_and_spaces = re.sub(r'[^A-Za-z\s]+', '', text)
    normalized = re.sub(r'\s+', ' ', letters_and_spaces).strip()
    return normalized.lower()


def diff_html(sentence1: str, sentence2: str) -> str:
    """Generate HTML diff output with colored spans."""
    words1 = sentence1.split()
    words2 = sentence2.split()

    matcher = difflib.SequenceMatcher(a=words1, b=words2)

    output = []

    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == "equal":
            output.extend(words1[i1:i2])
        elif tag == "delete":
            output.extend(f'<span class="deleted">{w}</span>' for w in words1[i1:i2])
        elif tag == "insert":
            output.extend(f'<span class="inserted">{w}</span>' for w in words2[j1:j2])
        elif tag == "replace":
            output.extend(f'<span class="deleted">{w}</span>' for w in words1[i1:i2])
            output.extend(f'<span class="inserted">{w}</span>' for w in words2[j1:j2])

    return " ".join(output)


def update_diff(event=None):
    """Update the diff output whenever input changes."""
    text1 = document["text1"].value
    text2 = document["text2"].value
    output_div = document["output"]

    # If either input is empty, show placeholder
    if not text1.strip() or not text2.strip():
        output_div.innerHTML = "Enter text in both boxes to see the word-level diff..."
        output_div.className = "output placeholder"
        return

    # Process the texts
    stream1 = to_word_stream(text1)
    stream2 = to_word_stream(text2)

    # Generate and display the diff
    diff_result = diff_html(stream1, stream2)
    output_div.innerHTML = diff_result
    output_div.className = "output"


# Set up event listeners
document["text1"].bind("input", update_diff)
document["text2"].bind("input", update_diff)
