import io

from docx import Document
from docx.opc.part import XmlPart
from docx.oxml.ns import qn

from adeu.models import DocumentEdit, ReviewAction
from adeu.redline.engine import RedlineEngine


def test_modern_comments_extended_update():
    """
    Simulates a document with existing commentsExtended.xml.
    Verifies that adding a reply updates this part.
    """
    doc = Document()
    doc.add_paragraph("Content")

    stream = io.BytesIO()
    doc.save(stream)
    stream.seek(0)

    # 1. Setup: Inject a fake commentsExtended part to simulate a modern doc
    # We do this by adding a comment normally, then manually attaching an extended part
    engine = RedlineEngine(stream)
    # NOTE: Must change text so the edit is not skipped as no-op
    engine.apply_edits([DocumentEdit(target_text="Content", new_text="Content Modified", comment="Root")])

    # Manually create commentsExtended part and relate it
    # We need the paraId of the comment we just added
    root_id = list(engine.comments_manager.extract_comments_data().keys())[0]

    # Find the paraId generated by our updated code
    # engine.comments_manager should be fresh? No, we need to inspect the one in memory
    comments_part = engine.comments_manager.comments_part
    root_comment = comments_part.element.find(qn("w:comment"))
    root_para_id = root_comment.find(qn("w:p")).get(qn("w14:paraId"))
    assert root_para_id is not None, "paraId should be generated"

    # Create extended part
    extended_xml = f"""
    <w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml">
      <w15:commentEx w15:paraId="{root_para_id}" w15:done="0"/>
    </w15:commentsEx>
    """
    package = engine.doc.part.package
    partname = package.next_partname("/word/commentsExtended%d.xml")
    reltype = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended"

    from docx.oxml import parse_xml

    extended_part = XmlPart(
        partname,
        "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",
        parse_xml(extended_xml),
        package,
    )
    package.parts.append(extended_part)
    engine.doc.part.relate_to(extended_part, reltype)

    # Save stream to persist this structure
    stream_modern = engine.save_to_stream()

    # 2. Test: Load this modern doc and Reply
    engine2 = RedlineEngine(stream_modern)

    # Verify it detected the extended part
    assert engine2.comments_manager.extended_part is not None, "Should detect existing commentsExtended part"

    action = ReviewAction(action="REPLY", target_id=f"Com:{root_id}", text="Reply")
    engine2.apply_review_actions([action])

    stream_final = engine2.save_to_stream()

    # 3. Inspect Result
    # Verify commentsExtended has the new entry linked to parent
    doc_final = Document(stream_final)
    extended_part_final = None
    for rel in doc_final.part.rels.values():
        if rel.reltype == reltype:
            extended_part_final = rel.target_part
            break

    assert extended_part_final is not None
    xml_final = extended_part_final.blob.decode("utf-8")

    print(xml_final)

    assert f'w15:paraIdParent="{root_para_id}"' in xml_final
    assert 'w15:done="0"' in xml_final
