import io
import mammoth
from ..models import DocumentContent, TextSegment


def parse_word(buffer: bytes) -> DocumentContent:
    result = mammoth.extract_raw_text(io.BytesIO(buffer))
    raw_text: str = result.value

    paragraphs = raw_text.split("\n")
    segments: list[TextSegment] = []
    char_offset = 0

    for paragraph in paragraphs:
        trimmed = paragraph.strip()
        if not trimmed:
            char_offset += len(paragraph) + 1
            continue

        idx = raw_text.find(trimmed, char_offset)
        if idx >= 0:
            segments.append(TextSegment(text=trimmed, charOffset=idx))
            char_offset = idx + len(trimmed)

    return DocumentContent(rawText=raw_text, segments=segments)
