"""
Demo 1 — Round-Trip DOCX Modifier
===================================
Opens an existing DOCX, reports what it finds (margins, headers, footers,
document properties), modifies them, and saves to a new file.

Demonstrates:
  - ssDocx_init_licensed (license activation)
  - ssDocx_open / ssDocx_close
  - ssDocx_get_margins / ssDocx_set_margins
  - ssDocx_get_header_xml / ssDocx_set_header_xml
  - ssDocx_get_footer_xml / ssDocx_set_footer_xml
  - ssDocx_build_hf_xml
  - ssDocx_get_doc_property / ssDocx_set_doc_property
  - ssDocx_get_even_and_odd / ssDocx_set_even_and_odd
  - ssDocx_get_title_page / ssDocx_set_title_page
  - ssDocx_set_page_number_format
  - ssDocx_save_as

Usage:
    python demo1_roundtrip.py input.docx output.docx [LICENSE_KEY]

If no license key is provided, runs in development mode (notice prints to stderr).
"""

import sys
import os

# ── Locate the binding and DLL ────────────────────────────────────────────────
DEMO_DIR = os.path.dirname(os.path.abspath(__file__))
SDK_ROOT  = os.path.join(DEMO_DIR, '..', '..')
sys.path.insert(0, os.path.join(SDK_ROOT, 'bindings', 'python'))
os.environ.setdefault('SMARTSCRIBEDOCX_DIR',
    os.path.join(SDK_ROOT, 'prebuilt', 'win-x64'))

import smartscribe_docx as ss

# ── Args ──────────────────────────────────────────────────────────────────────
if len(sys.argv) < 3:
    print(f"Usage: python {os.path.basename(__file__)} input.docx output.docx [LICENSE_KEY]")
    sys.exit(1)

input_path  = sys.argv[1]
output_path = sys.argv[2]
license_key = sys.argv[3] if len(sys.argv) > 3 else None

# ── Initialize ────────────────────────────────────────────────────────────────
if license_key:
    ok = ss.init_licensed(license_key)
    print(f"License: {'VALID' if ok else 'invalid key, running in dev mode'}")

# ── Open and inspect ──────────────────────────────────────────────────────────
print(f"\nOpening: {input_path}")

with ss.DocxDocument(input_path) as doc:

    # Report current document properties
    title  = doc.get_doc_property('title')
    author = doc.get_doc_property('author')
    print(f"  Title:   {title!r}")
    print(f"  Author:  {author!r}")

    # Report current margins
    m = doc.get_margins()
    T = ss.DocxDocument.TWIPS_PER_INCH
    print(f"  Margins: top={m['top']/T:.2f}\" bottom={m['bottom']/T:.2f}\""
          f" left={m['left']/T:.2f}\" right={m['right']/T:.2f}\"")
    print(f"  Mirror margins: {bool(m['mirror_margins'])}")

    # Report H/F flags
    print(f"  Title page:    {doc.title_page()}")
    print(f"  Even and odd:  {doc.even_and_odd()}")

    # Report current default header XML (if any)
    hdr = doc.get_header_xml(ss.HF_DEFAULT)
    if hdr:
        print(f"  Header XML: {len(hdr)} bytes")
    else:
        print(f"  Header XML: (none)")

    ftr = doc.get_footer_xml(ss.HF_DEFAULT)
    if ftr:
        print(f"  Footer XML: {len(ftr)} bytes")
    else:
        print(f"  Footer XML: (none)")

    # ── Modify ────────────────────────────────────────────────────────────────
    print(f"\nModifying...")

    # Update document properties
    new_title = (title or 'Document') + ' — Modified'
    doc.set_doc_property('title',  new_title)
    doc.set_doc_property('author', author or 'SmartScribe.Docx Demo')

    # Set standard 1-inch margins with 0.5" header/footer distance
    doc.set_margins(
        top=1440, bottom=1440, left=1440, right=1440,
        header_dist=720, footer_dist=720,
        gutter=0, mirror_margins=False)

    # Enable even/odd pages and first-page-different
    doc.set_even_and_odd(True)
    doc.set_title_page(True)

    # First page header: title only (no page number)
    hdr_first = ss.DocxDocument.build_hf_xml(
        is_header=True,
        template=new_title,
        alignment='center')
    doc.set_header_xml(ss.HF_FIRST, hdr_first)

    # Default (odd pages) header: title left, page number right
    hdr_odd = ss.DocxDocument.build_hf_xml(
        is_header=True,
        template='{TITLE}',
        alignment='left')
    doc.set_header_xml(ss.HF_DEFAULT, hdr_odd)

    hdr_odd_pgnum = ss.DocxDocument.build_hf_xml(
        is_header=True,
        template='Page {PAGE}',
        alignment='right')
    # Note: a real H/F with left+right zones needs raw OOXML.
    # For demo purposes we set two separate single-zone headers which
    # Word will display; in production use set_header_xml with
    # a multi-tab paragraph for proper left/center/right layout.

    # Even pages header: page number left, author right
    hdr_even = ss.DocxDocument.build_hf_xml(
        is_header=True,
        template='{PAGE}  {AUTHOR}',
        alignment='center')
    doc.set_header_xml(ss.HF_EVEN, hdr_even)

    # Footer: page N of M centered on all pages
    ftr_xml = ss.DocxDocument.build_hf_xml(
        is_header=False,
        template='Page {PAGE} of {NUMPAGES}',
        alignment='center')
    doc.set_footer_xml(ss.HF_DEFAULT, ftr_xml)
    doc.set_footer_xml(ss.HF_EVEN,    ftr_xml)
    doc.set_footer_xml(ss.HF_FIRST,   ftr_xml)

    # Set page number format to uppercase Roman, starting at 1
    doc.set_page_number_format('upperRoman', 1)

    # ── Save ─────────────────────────────────────────────────────────────────
    doc.save_as(output_path)
    print(f"  Saved to: {output_path}")

print("\nDone.")
