"""Tests for app.parsers.word — mirrors wordParser.test.ts.

Uses python-docx to build real .docx buffers from known content,
then asserts that parse_word + mammoth extract the correct segments.
"""
import io
import pytest
from docx import Document as DocxDocument
from ai_citer.parsers.word import parse_word
from ai_citer.ai.citation_mapper import map_citations
from ai_citer.models import ClaudeFact, ClaudeCitation


# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------

def build_docx(paragraphs: list[str]) -> bytes:
    """Create an in-memory .docx with the given paragraph strings."""
    doc = DocxDocument()
    for text in paragraphs:
        doc.add_paragraph(text)
    buf = io.BytesIO()
    doc.save(buf)
    return buf.getvalue()


# ---------------------------------------------------------------------------
# tests
# ---------------------------------------------------------------------------

def test_extracts_raw_text():
    buffer = build_docx(["Hello world.", "Second paragraph."])
    content = parse_word(buffer)
    assert "Hello world." in content.rawText
    assert "Second paragraph." in content.rawText


def test_produces_segments_for_each_paragraph():
    buffer = build_docx(["First.", "Second.", "Third."])
    content = parse_word(buffer)
    assert len(content.segments) >= 3


def test_char_offset_slices_reproduce_segment_text():
    buffer = build_docx(["Alpha paragraph.", "Beta paragraph."])
    content = parse_word(buffer)
    for seg in content.segments:
        sliced = content.rawText[seg.charOffset: seg.charOffset + len(seg.text)]
        assert sliced == seg.text


def test_char_offsets_are_non_decreasing():
    buffer = build_docx(["One.", "Two.", "Three.", "Four."])
    content = parse_word(buffer)
    for i in range(1, len(content.segments)):
        assert content.segments[i].charOffset > content.segments[i - 1].charOffset


def test_roundtrips_with_citation_mapper():
    buffer = build_docx([
        "The economic report confirmed a 7% growth rate.",
        "Unemployment fell to historic lows of 3.2 percent.",
    ])
    content = parse_word(buffer)
    facts = map_citations(content.rawText, [
        ClaudeFact(fact="growth", citations=[ClaudeCitation(exact_quote="7% growth rate")]),
        ClaudeFact(fact="unemployment", citations=[ClaudeCitation(exact_quote="3.2 percent")]),
    ])
    assert facts[0].citations[0].charOffset >= 0
    assert facts[0].citations[0].confidence == "exact"
    assert facts[1].citations[0].charOffset >= 0
    assert facts[1].citations[0].confidence == "exact"


def test_single_paragraph():
    buffer = build_docx(["Only paragraph."])
    content = parse_word(buffer)
    assert "Only paragraph." in content.rawText
    assert len(content.segments) >= 1
