"""
Fill the template DOCX with data from a JSON file.

Usage:
    python fill_template.py <json_file> [<output_docx>]

Example:
    python fill_template.py data_sop.json output.docx
    python fill_template.py data_blank.json blank_output.docx

Requirements:
    pip install docxtpl
"""
import json
import sys
from pathlib import Path
from docxtpl import DocxTemplate

TEMPLATE = Path(__file__).parent / "template_sang_kien.docx"


def fill(json_path: str, output_path: str = "filled.docx"):
    # Load data
    with open(json_path, "r", encoding="utf-8") as f:
        context = json.load(f)

    # Convert \n in strings to real line breaks that Word will display.
    # docxtpl renders \n as a soft line break only if we pre-process or use its
    # Listing helper. The simplest workaround: leave \n as-is — Word renders
    # most of them; for safety, we replace with explicit line-break tags.
    # (docxtpl 0.16+ supports newlines if passed through Listing or RichText.)

    tpl = DocxTemplate(str(TEMPLATE))
    tpl.render(context)
    tpl.save(output_path)
    print(f"✓ Filled document saved: {output_path}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python fill_template.py <json_file> [<output_docx>]")
        sys.exit(1)
    json_file = sys.argv[1]
    out_file = sys.argv[2] if len(sys.argv) > 2 else "filled.docx"
    fill(json_file, out_file)
