"""Render the editable journey Markdown to a Word document and printable HTML.
Uses Python's standard library only. Run from any directory.
"""
from pathlib import Path
from html import escape
import re
import zipfile
import xml.etree.ElementTree as ET

ROOT = Path(__file__).resolve().parent
source = (ROOT / 'CUSTOMER-JOURNEY.md').read_text()
blocks = []
lines = source.splitlines()
i = 0
while i < len(lines):
    line = lines[i].strip()
    if not line:
        i += 1
        continue
    if line.startswith('|'):
        rows = []
        while i < len(lines) and lines[i].strip().startswith('|'):
            cells = [c.strip() for c in lines[i].strip().strip('|').split('|')]
            if not all(re.fullmatch(r'[-: ]+', c) for c in cells):
                rows.append(cells)
            i += 1
        blocks.append(('table', rows))
        continue
    if line.startswith('[[SCREENSHOT '):
        blocks.append(('screenshot', line[13:-2].split(' | ', 2)))
    elif line.startswith('#'):
        level = len(line) - len(line.lstrip('#'))
        blocks.append(('h' + str(level), line[level:].strip()))
    else:
        blocks.append(('p', line))
    i += 1


def html_text(text):
    text = escape(text)
    return re.sub(r'https://[^\s<>]+', lambda m: '<a href="' + m[0].rstrip('.') + '">' + m[0].rstrip('.') + '</a>' + ('.' if m[0].endswith('.') else ''), text)

html = ['''<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Quatrohaus — Customer Journey and WhatsApp Charges</title>
<style>
:root{color-scheme:light}body{font:15px/1.65 Arial,sans-serif;color:#172d36;background:#eef3f4;margin:0}main{max-width:960px;background:white;margin:32px auto;padding:50px 60px}h1{font-size:32px;color:#08776c;border-bottom:4px solid #08776c;padding-bottom:18px}h2{margin-top:34px;color:#075c55}h3{margin-top:28px;color:#193a47}p{margin:12px 0}table{border-collapse:collapse;width:100%;font-size:12px;margin:22px 0}th,td{border:1px solid #cbd8dc;padding:9px;vertical-align:top;text-align:left}th{background:#e6f3ef}.screenshot{border:2px dashed #8da9ab;background:#f7faf9;padding:20px;margin:22px 0;break-inside:avoid}.screenshot strong{display:block;color:#075c55}.space{height:165px;display:flex;align-items:center;justify-content:center;color:#6a7f84;font-size:14px}.caption{font-size:12px;color:#546b73}a{color:#075c7b;overflow-wrap:anywhere}.toolbar{padding:12px;background:#e6f3ef;font-size:13px}@media print{body{background:white}main{margin:0;padding:0;max-width:none}.toolbar{display:none}h2,h3{break-after:avoid}table{font-size:9px}thead{display:table-header-group}a{color:inherit}.screenshot{background:white}.space{height:130px}@page{size:A4;margin:18mm}}
</style></head><body><main><div class="toolbar">Screenshot spaces are intentionally blank. Use the Word document to insert images. Print this page to PDF for sharing.</div>''']

W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
ET.register_namespace('w', W)

def w(tag, attrib=None):
    return ET.Element('{' + W + '}' + tag, {('{' + W + '}' + k): str(v) for k,v in (attrib or {}).items()})

def child(parent, tag, attrib=None):
    el = w(tag, attrib)
    parent.append(el)
    return el

def paragraph(parent, text, style=None, bold=False):
    p = child(parent, 'p')
    if style:
        child(child(p, 'pPr'), 'pStyle', {'val': style})
    r = child(p, 'r')
    if bold:
        child(child(r, 'rPr'), 'b')
    t = child(r, 't')
    t.text = text
    return p

def table(parent, rows, placeholder=False):
    t = child(parent, 'tbl')
    pr = child(t, 'tblPr')
    child(pr, 'tblW', {'w': 0, 'type': 'auto'})
    borders = child(pr, 'tblBorders')
    for side in ['top','left','bottom','right','insideH','insideV']:
        child(borders, side, {'val': 'dashed' if placeholder else 'single','sz': 6,'color': '9BB6B4'})
    for n, row in enumerate(rows):
        tr = child(t, 'tr')
        if placeholder:
            child(child(tr, 'trPr'), 'trHeight', {'val': 1900, 'hRule': 'atLeast'})
        elif n == 0:
            child(child(tr, 'trPr'), 'tblHeader')
        for value in row:
            tc = child(tr, 'tc')
            if n == 0:
                child(child(tc, 'tcPr'), 'shd', {'fill': 'E6F3EF'})
            paragraph(tc, value, bold=n == 0)
    paragraph(parent, '')


doc = w('document')
body = child(doc, 'body')
for kind, value in blocks:
    if kind.startswith('h'):
        html.append('<' + kind + '>' + html_text(value) + '</' + kind + '>')
        paragraph(body, value, {'h1':'Title','h2':'Heading1','h3':'Heading2'}.get(kind, 'Heading2'))
    elif kind == 'p':
        html.append('<p>' + html_text(value) + '</p>')
        paragraph(body, value)
    elif kind == 'table':
        html.append('<table><thead><tr>' + ''.join('<th>' + html_text(c) + '</th>' for c in value[0]) + '</tr></thead><tbody>')
        html.extend('<tr>' + ''.join('<td>' + html_text(c) + '</td>' for c in row) + '</tr>' for row in value[1:])
        html.append('</tbody></table>')
        table(body, value)
    else:
        sid, title, instruction = [s.strip() for s in value]
        html.append('<div class="screenshot"><strong>' + html_text(sid + ' — ' + title) + '</strong><div class="space">INSERT SCREENSHOT HERE</div><div class="caption">' + html_text(instruction) + '</div></div>')
        table(body, [[sid + ' — ' + title + '\n\nINSERT SCREENSHOT HERE\n\n' + instruction]], placeholder=True)
html.append('</main></body></html>')
(ROOT / 'CUSTOMER-JOURNEY.html').write_text('\n'.join(html))
sect = child(body, 'sectPr')
child(sect, 'pgSz', {'w':11906,'h':16838})
child(sect, 'pgMar', {'top':1000,'bottom':1000,'left':1000,'right':1000})
styles = w('styles')
defaults = child(styles, 'docDefaults')
rpr = child(child(defaults, 'rPrDefault'), 'rPr')
child(rpr, 'rFonts', {'ascii':'Calibri','hAnsi':'Calibri'})
child(rpr, 'sz', {'val':22})
for name, size in [('Normal',22),('Title',38),('Heading1',30),('Heading2',25)]:
    st = child(styles, 'style', {'type':'paragraph','styleId':name})
    child(st, 'name', {'val':name})
    pp = child(st, 'pPr')
    child(pp, 'spacing', {'after':160,'before':180 if name!='Normal' else 0})
    if name != 'Normal':
        child(pp, 'keepNext')
    rp = child(st, 'rPr')
    child(rp, 'sz', {'val':size})
    if name != 'Normal':
        child(rp, 'b')
        child(rp, 'color', {'val':'08776C'})
xml = lambda el: ET.tostring(el, encoding='utf-8', xml_declaration=True)
with zipfile.ZipFile(ROOT / 'CUSTOMER-JOURNEY.docx', 'w', zipfile.ZIP_DEFLATED) as z:
    z.writestr('[Content_Types].xml','''<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>''')
    z.writestr('_rels/.rels','''<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>''')
    z.writestr('word/_rels/document.xml.rels','''<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>''')
    z.writestr('word/document.xml', xml(doc))
    z.writestr('word/styles.xml', xml(styles))
print('Created Word and printable HTML documents with',sum(k=='screenshot' for k,v in blocks),'screenshot placeholders.')
