"""A labeled derivative without repeated/orphan notes for legacy writer controls."""
from pathlib import Path
from zipfile import ZipFile,ZipInfo,ZIP_DEFLATED
from io import BytesIO
from lxml import etree
import sys,json,hashlib
source,out=map(Path,sys.argv[1:3]);assert not out.exists(),'Never overwrite a retained fixture'
W='http://schemas.openxmlformats.org/wordprocessingml/2006/main';ns={'w':W}
with ZipFile(source) as z:parts={n:z.read(n) for n in z.namelist()}
body=etree.fromstring(parts['word/document.xml']);refs=body.xpath('//w:footnoteReference',namespaces=ns)
assert [r.get('{'+W+'}id') for r in refs]==['7','7','21']
refs[0].set('{'+W+'}id','1');refs[2].set('{'+W+'}id','2')
replacement=etree.Element('{'+W+'}t');replacement.text=' (see the first note)';refs[1].getparent().replace(refs[1],replacement)
for r in body.xpath('//w:endnoteReference',namespaces=ns):r.set('{'+W+'}id',{'3':'1','9':'2'}[r.get('{'+W+'}id')])
parts['word/document.xml']=etree.tostring(body,xml_declaration=True,encoding='UTF-8',standalone=True)
for kind,mapping in [('footnote',{'7':'1','21':'2'}),('endnote',{'3':'1','9':'2'})]:
    part='word/'+kind+'s.xml';root=etree.fromstring(parts[part])
    for note in list(root):
        if note.get('{'+W+'}type'):continue
        old=note.get('{'+W+'}id')
        if old not in mapping:root.remove(note)
        else:note.set('{'+W+'}id',mapping[old])
    parts[part]=etree.tostring(root,xml_declaration=True,encoding='UTF-8',standalone=True)
target=BytesIO()
with ZipFile(target,'w',ZIP_DEFLATED,compresslevel=9) as z:
    for name,data in parts.items():
        info=ZipInfo(name,(2020,1,1,0,0,0));info.compress_type=ZIP_DEFLATED;z.writestr(info,data)
data=target.getvalue();out.write_bytes(data)
print(json.dumps(dict(source=str(source),sourceSha256=hashlib.sha256(source.read_bytes()).hexdigest(),file=str(out),bytes=len(data),sha256=hashlib.sha256(data).hexdigest(),separateOriginalBodyCorpus=False,variant='Sequential referenced note IDs; repeated reference becomes literal see-first-note text; orphan note removed. Original rich OpenXML controls stay unchanged.')))
