from pathlib import Path

from docx import Document


ROOT = Path(__file__).resolve().parents[1]


def build_docx(source: Path, target: Path) -> None:
    markdown = source.read_text(encoding="utf-8")
    document = Document()
    in_code_block = False
    table_buffer: list[list[str]] = []

    def flush_table() -> None:
        nonlocal table_buffer
        if not table_buffer:
            return

        headers = table_buffer[0]
        rows = table_buffer[1:]
        table = document.add_table(rows=1, cols=len(headers))
        table.style = "Table Grid"

        for index, value in enumerate(headers):
            table.rows[0].cells[index].text = value

        for row in rows:
            cells = table.add_row().cells
            for index, value in enumerate(row):
                if index < len(cells):
                    cells[index].text = value

        table_buffer = []

    def is_table_separator(cells: list[str]) -> bool:
        return all(cell and set(cell) <= {"-", ":"} for cell in cells)

    def parse_table_row(line: str) -> list[str] | None:
        stripped = line.strip()
        if not stripped.startswith("|") or not stripped.endswith("|"):
            return None
        return [cell.strip() for cell in stripped.strip("|").split("|")]

    for raw_line in markdown.splitlines():
        line = raw_line.rstrip()

        if line.startswith("```"):
            flush_table()
            in_code_block = not in_code_block
            continue

        if in_code_block:
            paragraph = document.add_paragraph()
            paragraph.style = "No Spacing"
            paragraph.add_run(line)
            continue

        table_row = parse_table_row(line)
        if table_row:
            if is_table_separator(table_row):
                continue
            table_buffer.append(table_row)
            continue

        flush_table()

        if not line.strip():
            document.add_paragraph("")
            continue

        if line.startswith("# "):
            document.add_heading(line[2:].strip(), level=0)
            continue

        if line.startswith("## "):
            document.add_heading(line[3:].strip(), level=1)
            continue

        if line.startswith("### "):
            document.add_heading(line[4:].strip(), level=2)
            continue

        if line.startswith("#### "):
            document.add_heading(line[5:].strip(), level=3)
            continue

        if line.startswith("- "):
            document.add_paragraph(line[2:].strip(), style="List Bullet")
            continue

        document.add_paragraph(line)

    flush_table()
    document.save(target)


if __name__ == "__main__":
    build_docx(ROOT / "docs" / "TECHNICAL_DOCUMENTATION.md", ROOT / "docs" / "TECHNICAL_DOCUMENTATION.docx")
