"""
Demo 2 — DOCX Authoring from HTML
====================================
Creates a professional-looking DOCX entirely from HTML content.
No input file needed — generates a complete document from scratch.

Demonstrates:
  - ssDocx_write_html (one-shot creation from HTML)
  - ssDocx_open (re-open to set margins/H/F)
  - Full heading hierarchy (H1-H3)
  - Paragraphs with inline bold/italic/underline
  - Ordered and unordered lists
  - Hyperlinks
  - Document properties
  - Margins set to book-standard (6x9 equivalent)
  - Running header with chapter reference
  - Page-numbered footer

Usage:
    python demo2_authoring.py output.docx [LICENSE_KEY]
"""

import sys
import os

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

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

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

if license_key:
    ss.init_licensed(license_key)

# ── Document content as HTML ──────────────────────────────────────────────────
HTML = """
<h1>SmartScribe.Docx SDK</h1>
<h2>Developer Reference Guide</h2>

<h2>Introduction</h2>
<p>
The <b>SmartScribe.Docx SDK</b> is a native C++ library for reading and writing
DOCX files with correct ECMA-376 specification compliance. It is exposed through
a pure C API, making it callable from <b>C</b>, <b>C++</b>, <i>Python</i>,
<i>C#</i>, and any language with a C foreign function interface.
</p>
<p>
This guide demonstrates core authoring capabilities including structured headings,
inline formatting, lists, and document property management.
</p>

<h2>1. Getting Started</h2>

<h3>1.1 Initialization</h3>
<p>
Call <b>ssDocx_init_licensed()</b> once at application startup with your
license key. In development, call <b>ssDocx_init()</b> without a key — the
library prints a one-line notice to stderr and continues normally.
</p>

<h3>1.2 Creating a Document</h3>
<p>
The fastest path from HTML to DOCX is the <b>write_html</b> function:
</p>

<h2>2. Core API</h2>

<h3>2.1 Margins</h3>
<p>
All margin values are specified in <b>twips</b>. One inch equals
<b>1440 twips</b>. One centimetre equals approximately <b>567 twips</b>.
The SDK supports all eight margin values defined in ECMA-376:
</p>
<ul>
<li>Top and bottom page margins</li>
<li>Left and right (or inner and outer when mirror margins are enabled)</li>
<li>Header distance from top edge</li>
<li>Footer distance from bottom edge</li>
<li>Gutter margin (for binding)</li>
<li>Mirror margins flag (swaps left/right on even-numbered pages)</li>
</ul>

<h3>2.2 Headers and Footers</h3>
<p>
The SDK supports <b>three header/footer variants</b> per document section,
matching Microsoft Word's implementation:
</p>
<ol>
<li><b>Default</b> — applies to odd pages (or all pages when even/odd is off)</li>
<li><b>Even</b> — applies to even pages when even-and-odd headers are enabled</li>
<li><b>First</b> — applies to the first page when title-page is enabled</li>
</ol>
<p>
Headers and footers are stored as raw OOXML. The SDK provides a builder
function that creates valid OOXML from template strings using variables
including <b>{PAGE}</b>, <b>{NUMPAGES}</b>, <b>{TITLE}</b>, and <b>{AUTHOR}</b>.
</p>

<h3>2.3 Document Properties</h3>
<p>
Document core properties — title, author, subject, description, keywords,
and category — are stored in <i>docProps/core.xml</i> within the DOCX
container. The SDK reads and writes these properties through a simple
key-value interface. Properties set here appear in Windows Explorer's
file details pane and in Word's Document Properties dialog.
</p>

<h2>3. License Tiers</h2>
<p>
SmartScribe.Docx is available under six license tiers, from a free development
license to a full source license. The <b>Indie tier</b> is free for projects
grossing under <b>$100,000 per year</b> and requires annual registration.
Paid tiers start at <b>$299</b> for a single-application deployment license.
</p>

<h2>Conclusion</h2>
<p>
SmartScribe.Docx delivers <i>correct</i> DOCX implementation where others
compromise. The six-layer ECMA-376 style cascade, correct toggle property
XOR behavior, and four-slot font resolution model are implemented as
specified — not approximated.
</p>
<p>
For licensing and support, visit <b>https://smartscribepro.com/docx-sdk</b>.
</p>
"""

print(f"Creating: {output_path}")

# ── One-shot creation from HTML ───────────────────────────────────────────────
ss.DocxDocument.write_html(output_path, HTML)
print(f"  HTML → DOCX complete ({len(HTML):,} bytes of HTML)")

# ── Re-open to set margins, H/F and document properties ──────────────────────
with ss.DocxDocument(output_path) as doc:

    # Book-standard margins: 1" top/bottom, 1.25" sides (common for 6x9)
    doc.set_margins(
        top=1440, bottom=1440,
        left=1800, right=1440,   # slightly wider left gutter
        header_dist=720, footer_dist=720,
        gutter=0, mirror_margins=True)   # mirror for duplex printing

    # Document properties
    doc.set_doc_property('title',       'SmartScribe.Docx SDK Developer Reference')
    doc.set_doc_property('author',      'Gain Publications')
    doc.set_doc_property('subject',     'DOCX SDK API Reference')
    doc.set_doc_property('description', 'Demonstrates SmartScribe.Docx authoring capabilities.')
    doc.set_doc_property('keywords',    'DOCX, SDK, ECMA-376, C++, Python, .NET')

    # Enable even/odd headers for duplex
    doc.set_even_and_odd(True)
    doc.set_title_page(False)  # no special first-page header for this doc

    # Odd pages: title on left
    hdr_odd = ss.DocxDocument.build_hf_xml(
        is_header=True,
        template='SmartScribe.Docx SDK',
        alignment='left')
    doc.set_header_xml(ss.HF_DEFAULT, hdr_odd)

    # Even pages: author on right
    hdr_even = ss.DocxDocument.build_hf_xml(
        is_header=True,
        template='Gain Publications',
        alignment='right')
    doc.set_header_xml(ss.HF_EVEN, hdr_even)

    # Footer: page number centered on all pages
    ftr = ss.DocxDocument.build_hf_xml(
        is_header=False,
        template='{PAGE}',
        alignment='center')
    doc.set_footer_xml(ss.HF_DEFAULT, ftr)
    doc.set_footer_xml(ss.HF_EVEN,    ftr)

    # Decimal page numbering starting at 1
    doc.set_page_number_format('decimal', 1)

    doc.save()
    print(f"  Margins, properties, headers/footers applied.")

print(f"\nOutput: {output_path}")
print("Open in Microsoft Word to verify layout.")
