"""Reproduce the run-formatting example at vespper.com/guides/python-docx.

Requires python-docx==1.2.0. Run in an empty working directory.
Writes three DOCX files in that directory; rerunning replaces those files.
"""

from pathlib import Path

from docx import Document


def create_proposal(output: Path) -> None:
    document = Document()
    document.core_properties.author = "Vespper"
    document.core_properties.title = "Project proposal"
    title = document.add_paragraph()
    title.add_run("Project proposal").bold = True
    paragraph = document.add_paragraph("The draft is due on ")
    paragraph.add_run("Friday").bold = True
    paragraph.add_run(".")
    document.add_paragraph("Prepare a draft for review", style="List Bullet")
    document.add_paragraph("Collect feedback", style="List Bullet")
    document.save(output)


def main() -> None:
    original = Path("proposal.docx")
    create_proposal(original)

    paragraph_edit = Document(original)
    for paragraph in paragraph_edit.paragraphs:
        if "Friday" in paragraph.text:
            paragraph.text = paragraph.text.replace("Friday", "Monday")
    paragraph_edit.save("proposal-paragraph-edit.docx")

    run_edit = Document(original)
    replacements = 0
    for paragraph in run_edit.paragraphs:
        for run in paragraph.runs:
            if "Friday" in run.text:
                replacements += run.text.count("Friday")
                run.text = run.text.replace("Friday", "Monday")
    if replacements != 1:
        raise ValueError(f"Expected one deadline, found {replacements}")
    run_edit.save("proposal-run-edit.docx")

    print("Created proposal.docx, proposal-paragraph-edit.docx, and proposal-run-edit.docx")


if __name__ == "__main__":
    main()
