"""Reproduce a synthetic DOCX conversion; no credentials or model service used.

Install the adjacent requirements.txt in a Python virtual environment, then run:
  python run.py --output ./experiment-output
The default output is a new local directory, never the published evidence files.
"""
import argparse
from datetime import datetime, timezone
import hashlib
from importlib.metadata import version
import io
import json
from pathlib import Path
import platform
import sys
import zipfile

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.opc.constants import RELATIONSHIP_TYPE
from markitdown import MarkItDown

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=Path("experiment-output"))
args = parser.parse_args()
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=True)
if any((out / name).exists() for name in ["input.docx", "output.md", "report.json"]):
    raise SystemExit("Choose an empty output directory; existing evidence is preserved.")

doc = Document()
doc.core_properties.title = "Project Cedar — synthetic conversion fixture"
doc.core_properties.author = "Artificially Nerdy"
doc.core_properties.created = datetime(2026, 10, 15, tzinfo=timezone.utc)
doc.core_properties.modified = datetime(2026, 10, 15, tzinfo=timezone.utc)
doc.add_heading("Project Cedar meeting notes", level=1)
doc.add_paragraph("Synthetic example only. No real customer, meeting or budget is represented.")
doc.add_paragraph("Budget approved: MYR 1,200.00. Review date: 18 October 2026.")
doc.add_heading("Next actions", level=2)
doc.add_paragraph("Prepare the project brief", style="List Bullet")
doc.add_paragraph("Check the figures against the original document", style="List Bullet")
table = doc.add_table(rows=1, cols=3)
for cell, text in zip(table.rows[0].cells, ["Task", "Owner", "Due"]):
    cell.text = text
for row in [["Prepare brief", "Alex", "18 October 2026"], ["Review budget", "Morgan", "19 October 2026"]]:
    for cell, text in zip(table.add_row().cells, row):
        cell.text = text
p = doc.add_paragraph("Reference: ")
link = OxmlElement("w:hyperlink")
link.set(qn("r:id"), doc.part.relate_to("https://artificiallynerdy.com/", RELATIONSHIP_TYPE.HYPERLINK, is_external=True))
run = OxmlElement("w:r")
text = OxmlElement("w:t")
text.text = "Artificially Nerdy"
run.append(text)
link.append(run)
p._p.append(link)
doc.sections[0].header.paragraphs[0].text = "SYNTHETIC HEADER: check this separately"
doc.sections[0].footer.paragraphs[0].text = "SYNTHETIC FOOTER: demonstration only"

# Stable ZIP metadata makes this synthetic input reproducible.
buffer = io.BytesIO()
doc.save(buffer)
with zipfile.ZipFile(buffer) as original, zipfile.ZipFile(out / "input.docx", "w", compression=zipfile.ZIP_DEFLATED) as fixture:
    for name in sorted(original.namelist()):
        info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
        info.compress_type = zipfile.ZIP_DEFLATED
        fixture.writestr(info, original.read(name))

network_attempts = []
def audit(event, args):
    if event in {"socket.connect", "socket.getaddrinfo"}:
        network_attempts.append(event)
        raise RuntimeError("Network access is blocked during this conversion experiment")
sys.addaudithook(audit)

converter = MarkItDown(enable_plugins=False)
result = converter.convert_local(str(out / "input.docx"))
markdown = result.text_content
(out / "output.md").write_text(markdown, encoding="utf-8")
checks = [
    {"id": "heading", "description": "Main heading survives as a Markdown heading", "passed": "# Project Cedar meeting notes" in markdown},
    {"id": "subheading", "description": "Next-actions subheading survives", "passed": "## Next actions" in markdown},
    {"id": "list", "description": "Both action items survive as list items", "passed": all(any(line.lstrip().startswith(("* ", "- ", "+ ")) and item in line for line in markdown.splitlines()) for item in ["Prepare the project brief", "Check the figures against the original document"])},
    {"id": "table", "description": "The two-row task table and named columns survive", "passed": all(value in markdown for value in ["| Task | Owner | Due |", "| Prepare brief | Alex | 18 October 2026 |", "| Review budget | Morgan | 19 October 2026 |"])},
    {"id": "number-date", "description": "The sample budget and review date survive unchanged", "passed": "MYR 1,200.00" in markdown and "18 October 2026" in markdown},
    {"id": "link", "description": "The hyperlink label and URL survive", "passed": "[Artificially Nerdy](https://artificiallynerdy.com/)" in markdown},
    {"id": "no-network", "description": "No Python network connection or DNS lookup was attempted during conversion", "passed": not network_attempts},
]
observations = [
    {"id": "header", "description": "Word page-header text appears in converted Markdown", "present": "SYNTHETIC HEADER" in markdown},
    {"id": "footer", "description": "Word page-footer text appears in converted Markdown", "present": "SYNTHETIC FOOTER" in markdown},
]
report = {
    "id": "markitdown-docx-2026-10-15",
    "kind": "local_test",
    "testedAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
    "status": "passed" if all(c["passed"] for c in checks) else "failed",
    "synthetic": True,
    "environment": {"python": platform.python_version(), "system": platform.system(), "machine": platform.machine(), "markitdown": version("markitdown"), "python-docx": version("python-docx")},
    "method": "One generated DOCX converted with MarkItDown.convert_local; third-party plugins disabled, no model client or cloud extraction configured, Python network audit hook denies connection and DNS events during conversion.",
    "checks": checks,
    "observations": observations,
    "limitations": ["One synthetic Word file, not a representative document benchmark.", "No PDF, OCR, images, tracked changes, scanned pages or cloud extraction were tested.", "No AI answer-quality, speed or productivity improvement was measured.", "Network observations cover Python audit events in this configured conversion, not every possible plugin or native library."],
    "artifacts": [{"file": name, "sha256": hashlib.sha256((out / name).read_bytes()).hexdigest(), "bytes": (out / name).stat().st_size} for name in ["input.docx", "output.md"]],
}
(out / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2))
if report["status"] != "passed":
    raise SystemExit(1)
