"""Original CC0 note corpus; python-docx's MIT default template is retained."""
from pathlib import Path
from zipfile import ZipFile,ZIP_DEFLATED,ZipInfo
from io import BytesIO
import json,hashlib,sys
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from lxml import etree
out=Path(sys.argv[1]);out.mkdir(parents=True,exist_ok=False)
W='http://schemas.openxmlformats.org/wordprocessingml/2006/main';R='http://schemas.openxmlformats.org/package/2006/relationships';CT='http://schemas.openxmlformats.org/package/2006/content-types'
doc=Document();doc.core_properties.title='Original referenced notes — café Ω';doc.core_properties.author='Tabmorph CC0 fixture author'
doc.add_heading('Referenced note control',0)
p=doc.add_paragraph('BODY START — café Ω Привет 日本語. First note')
def reference(paragraph,kind,number):
    run=OxmlElement('w:r');node=OxmlElement('w:'+kind+'Reference');node.set(qn('w:id'),str(number));run.append(node);paragraph._p.append(run)
reference(p,'footnote',7);p.add_run(' then endnote');reference(p,'endnote',3);p.add_run('.')
p=doc.add_paragraph('Repeat the first note');reference(p,'footnote',7);p.add_run(' and add another');reference(p,'footnote',21);p.add_run(' with a final endnote');reference(p,'endnote',9);p.add_run('.')
p=doc.add_paragraph();p.add_run('Literal TAB:');p.add_run('\t');p.add_run('after tab');p.add_run().add_break();p.add_run('after line break. ')
cr=OxmlElement('w:cr');p.add_run()._r.append(cr);p.add_run('after carriage break.')
table=doc.add_table(rows=1,cols=2);table.cell(0,0).text='BODY CELL A';table.cell(0,1).text='BODY CELL B'
doc.add_paragraph('BODY END. Notes below belong to their markers.')
temp=BytesIO();doc.save(temp)
with ZipFile(BytesIO(temp.getvalue())) as z: members={n:z.read(n) for n in z.namelist()}
def note_part(kind,items):
    root=etree.Element('{'+W+'}'+kind+'s',nsmap={'w':W})
    sep=etree.SubElement(root,'{'+W+'}'+kind);sep.set('{'+W+'}id','-1');sep.set('{'+W+'}type','separator')
    for number,paragraphs in items:
        note=etree.SubElement(root,'{'+W+'}'+kind);note.set('{'+W+'}id',str(number))
        for text in paragraphs:
            p=etree.SubElement(note,'{'+W+'}p');r=etree.SubElement(p,'{'+W+'}r');t=etree.SubElement(r,'{'+W+'}t');t.set('{http://www.w3.org/XML/1998/namespace}space','preserve');t.text=text
    return etree.tostring(root,xml_declaration=True,encoding='UTF-8',standalone=True)
footnotes=[(7,['FOOTNOTE ALPHA — café Ω Привет 日本語.','Second paragraph in the first footnote.']),(21,['FOOTNOTE BETA — literal <tag> & symbols 😀.']),(55,['UNREFERENCED NOTE MUST NOT BE EXPORTED'])]
endnotes=[(3,['ENDNOTE GAMMA — Ελληνικά and Кириллица.']),(9,['ENDNOTE DELTA — 日本語 stays literal.'])]
members['word/footnotes.xml']=note_part('footnote',footnotes);members['word/endnotes.xml']=note_part('endnote',endnotes)
ct=etree.fromstring(members['[Content_Types].xml']);rels=etree.fromstring(members['word/_rels/document.xml.rels'])
for kind in ['footnotes','endnotes']:
    entry=etree.SubElement(ct,'{'+CT+'}Override');entry.set('PartName','/word/'+kind+'.xml');entry.set('ContentType','application/vnd.openxmlformats-officedocument.wordprocessingml.'+kind+'+xml')
    relation=etree.SubElement(rels,'{'+R+'}Relationship');relation.set('Id','original-'+kind);relation.set('Type','http://schemas.openxmlformats.org/officeDocument/2006/relationships/'+kind);relation.set('Target',kind+'.xml')
members['[Content_Types].xml']=etree.tostring(ct,xml_declaration=True,encoding='UTF-8',standalone=True);members['word/_rels/document.xml.rels']=etree.tostring(rels,xml_declaration=True,encoding='UTF-8',standalone=True)
def archive(parts):
    target=BytesIO()
    with ZipFile(target,'w',ZIP_DEFLATED,compresslevel=9) as z:
        for name,value in parts.items():
            info=ZipInfo(name,(2020,1,1,0,0,0));info.compress_type=ZIP_DEFLATED;z.writestr(info,value)
    return target.getvalue()
rows=[]
for form,mime in [('docx','application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'),('docm','application/vnd.ms-word.document.macroEnabled.main+xml'),('dotx','application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml')]:
    parts=dict(members);tree=etree.fromstring(parts['[Content_Types].xml'])
    for e in tree:
        if e.get('PartName')=='/word/document.xml':e.set('ContentType',mime)
    parts['[Content_Types].xml']=etree.tostring(tree,xml_declaration=True,encoding='UTF-8',standalone=True)
    data=archive(parts);name='notes.'+form;(out/name).write_bytes(data);rows.append(dict(file=name,bytes=len(data),sha256=hashlib.sha256(data).hexdigest()))
utf16=dict(members)
for part in ['word/document.xml','word/footnotes.xml','word/endnotes.xml']:
    utf16[part]=etree.tostring(etree.fromstring(utf16[part]),xml_declaration=True,encoding='UTF-16',standalone=True)
data=archive(utf16);(out/'notes-utf16.docx').write_bytes(data);rows.append(dict(file='notes-utf16.docx',bytes=len(data),sha256=hashlib.sha256(data).hexdigest()))
manifest=dict(originalBodyCorpora=1,sourceWrappers=3,encodingDerivatives=1,license='Original authored body/notes CC0; python-docx1.2.0 default template MIT.',developerOnly=True,noUserFiles=True,rows=rows,referenceOrder=['[Footnote 1]','[Endnote 1]','[Footnote 1]','[Footnote 2]','[Endnote 2]'],noteOrder=['[Footnote 1]','[Endnote 1]','[Footnote 2]','[Endnote 2]'],noteText=[paragraph for _,paragraphs in footnotes[:2]+endnotes for paragraph in paragraphs],unreferencedText='UNREFERENCED NOTE MUST NOT BE EXPORTED',numbering='Renumber separately by first reference per note type; repeated references reuse one marker/body. Source custom/restarted/Roman formatting is not retained.',writer='python-docx1.2.0 + lxml original OOXML notes')
(out/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
(out/'LICENSE.txt').write_text('Original authored body/notes: CC0-1.0. No user files. The default package template derives from python-docx1.2.0 under its retained MIT license.\n')
print(json.dumps({'files':len(rows),'bodyCorpora':1,'sourceWrappers':3,'encodingDerivatives':1}))
