#!/usr/bin/env python3
"""為 Pandoc 產生的 docx 檔案加上表格邊框與樣式"""
import sys
from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml

def set_cell_border(cell, **kwargs):
    """Set cell border. Usage: set_cell_border(cell, top={"sz": 6, "color": "000000"}, ...)"""
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcBorders = parse_xml(f'<w:tcBorders {nsdecls("w")}></w:tcBorders>')
    for edge, attrs in kwargs.items():
        element = parse_xml(
            f'<w:{edge} {nsdecls("w")} w:val="single" w:sz="{attrs.get("sz", 4)}" '
            f'w:space="0" w:color="{attrs.get("color", "000000")}"/>'
        )
        tcBorders.append(element)
    tcPr.append(tcBorders)

def style_tables(docx_path):
    doc = Document(docx_path)

    for table in doc.tables:
        # Set table width to full page
        table.autofit = True

        for i, row in enumerate(table.rows):
            for cell in row.cells:
                # Add borders to all cells
                border = {"sz": 4, "color": "AAAAAA"}
                set_cell_border(cell, top=border, bottom=border, start=border, end=border)

                # Style cell text
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.size = Pt(9)

                # Header row styling
                if i == 0:
                    shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="E8EDF2" w:val="clear"/>')
                    cell._tc.get_or_add_tcPr().append(shading)
                    for paragraph in cell.paragraphs:
                        for run in paragraph.runs:
                            run.font.bold = True
                            run.font.size = Pt(9)
                            run.font.color.rgb = RGBColor(0x33, 0x33, 0x33)

                # Alternating row colors
                elif i % 2 == 0:
                    shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="F8F9FA" w:val="clear"/>')
                    cell._tc.get_or_add_tcPr().append(shading)

    doc.save(docx_path)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: fix-docx-tables.py <file.docx>")
        sys.exit(1)
    style_tables(sys.argv[1])
