"""Convert agent_design_blueprint.md to a Word document."""

import re
from pathlib import Path
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.oxml import parse_xml
from docx.oxml.ns import qn

md_path = Path(__file__).parent / "agent_design_blueprint.md"
out_path = Path(__file__).parent / "agent_design_blueprint.docx"

doc = Document()

# -- Style setup --
style = doc.styles["Normal"]
style.font.name = "Calibri"
style.font.size = Pt(11)
style.paragraph_format.space_after = Pt(6)

for level in range(1, 4):
    hs = doc.styles[f"Heading {level}"]
    hs.font.name = "Calibri"
    hs.font.color.rgb = RGBColor(0x2B, 0x6C, 0xB0)

for section in doc.sections:
    section.top_margin = Inches(0.8)
    section.bottom_margin = Inches(0.8)
    section.left_margin = Inches(1.0)
    section.right_margin = Inches(1.0)


def _add_inline(paragraph, text):
    """Parse inline markdown (**bold**, *italic*, `code`) and add runs."""
    parts = re.split(r'(\*\*.*?\*\*|\*[^*]+\*|`[^`]+`)', text)
    for part in parts:
        if part.startswith("**") and part.endswith("**"):
            run = paragraph.add_run(part[2:-2])
            run.bold = True
            run.font.size = Pt(11)
        elif part.startswith("*") and part.endswith("*") and not part.startswith("**"):
            run = paragraph.add_run(part[1:-1])
            run.italic = True
            run.font.size = Pt(11)
        elif part.startswith("`") and part.endswith("`"):
            run = paragraph.add_run(part[1:-1])
            run.font.name = "Consolas"
            run.font.size = Pt(10)
            run.font.color.rgb = RGBColor(0x88, 0x33, 0x33)
        else:
            run = paragraph.add_run(part)
            run.font.size = Pt(11)


def _add_code_block(code_text):
    """Add a code block paragraph with gray background."""
    p = doc.add_paragraph()
    p.paragraph_format.space_before = Pt(4)
    p.paragraph_format.space_after = Pt(4)
    run = p.add_run(code_text)
    run.font.name = "Consolas"
    run.font.size = Pt(9)
    run.font.color.rgb = RGBColor(0x33, 0x33, 0x33)
    shading = parse_xml(
        '<w:shd w:fill="F2F2F2" w:val="clear" '
        'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>'
    )
    p.paragraph_format.element.get_or_add_pPr().append(shading)


# -- Parse and convert --
text = md_path.read_text(encoding="utf-8")
lines = text.split("\n")

i = 0
while i < len(lines):
    line = lines[i]

    # Skip horizontal rules
    if line.strip() == "---":
        i += 1
        continue

    # Headings
    if line.startswith("### "):
        doc.add_heading(line[4:].strip(), level=3)
        i += 1
        continue
    if line.startswith("## "):
        doc.add_heading(line[3:].strip(), level=2)
        i += 1
        continue
    if line.startswith("# "):
        doc.add_heading(line[2:].strip(), level=1)
        i += 1
        continue

    # Code blocks
    if line.strip().startswith("```"):
        code_lines = []
        i += 1
        while i < len(lines) and not lines[i].strip().startswith("```"):
            code_lines.append(lines[i])
            i += 1
        i += 1  # skip closing ```
        _add_code_block("\n".join(code_lines))
        continue

    # Bullet lists
    if line.strip().startswith("- "):
        content = line.strip()[2:]
        p = doc.add_paragraph(style="List Bullet")
        _add_inline(p, content)
        i += 1
        while i < len(lines) and lines[i].startswith("  ") and not lines[i].strip().startswith("- "):
            _add_inline(p, " " + lines[i].strip())
            i += 1
        continue

    # Empty lines
    if not line.strip():
        i += 1
        continue

    # Regular paragraph (collect continuation lines)
    p = doc.add_paragraph()
    para_lines = [line.strip()]
    i += 1
    while (i < len(lines) and lines[i].strip()
           and not lines[i].startswith("#")
           and not lines[i].startswith("```")
           and not lines[i].strip().startswith("- ")
           and lines[i].strip() != "---"):
        para_lines.append(lines[i].strip())
        i += 1
    _add_inline(p, " ".join(para_lines))

doc.save(out_path)
print(f"Saved: {out_path}")
