"""Independent ZIP/lxml document readers; developer-only, never app code."""
from zipfile import ZipFile
from lxml import etree
import re,unicodedata,hashlib
ns=dict(w='http://schemas.openxmlformats.org/wordprocessingml/2006/main',
        text='urn:oasis:names:tc:opendocument:xmlns:text:1.0',
        office='urn:oasis:names:tc:opendocument:xmlns:office:1.0',
        style='urn:oasis:names:tc:opendocument:xmlns:style:1.0',
        meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
        dc='http://purl.org/dc/elements/1.1/')
W='{'+ns['w']+'}'; T='{'+ns['text']+'}'
sha=lambda b:hashlib.sha256(b).hexdigest()
norm=lambda t:re.sub(r'\s+',' ',unicodedata.normalize('NFC',t)).strip()
parser=etree.XMLParser(resolve_entities=False,no_network=True)
def xml(z,name):return etree.fromstring(z.read(name),parser)
def word_inline(node):
    if node.tag==W+'t':return node.text or ''
    if node.tag in (W+'tab',W+'br',W+'cr'):return ' '
    return ''.join(word_inline(child) for child in node)+('\n' if node.tag==W+'p' else '')
def word_text(node):return norm(word_inline(node))
def odf_inline(node):
    if node.tag in (T+'note','{'+ns['office']+'}annotation'):return ''
    if node.tag==T+'s':return ' '*int(node.get(T+'c','1'))
    if node.tag in (T+'tab',T+'line-break'):return ' '
    return (node.text or '')+''.join(odf_inline(child)+(child.tail or '') for child in node)+('\n' if node.tag in (T+'p',T+'h') else '')
def paragraphs(node,source=False):
    items=node.findall('.//'+W+'p') if source else node.xpath('.//text:p[not(ancestor::text:note or ancestor::office:annotation)] | .//text:h[not(ancestor::text:note or ancestor::office:annotation)]',namespaces=ns)
    return [t for n in items if (t:=word_text(n) if source else norm(odf_inline(n)))]
def source_features(source):
    with ZipFile(source) as z:
        main=xml(z,'word/document.xml');body=main.find(W+'body');notes=[]
        for kind in ['footnote','endnote']:
            refs=main.findall('.//'+W+kind+'Reference')
            if not refs:continue
            root=xml(z,'word/'+kind+'s.xml')
            for identity in dict.fromkeys(n.get(W+'id') for n in refs):
                matching=[n for n in root if n.get(W+'id')==identity];assert len(matching)==1
                notes.append(dict(kind=kind,id=identity,text=word_text(matching[0])))
        note_map={(n['kind'],n['id']):n['text'] for n in notes}
        reference_order=[dict(kind='footnote' if n.tag==W+'footnoteReference' else 'endnote',text=note_map[('footnote' if n.tag==W+'footnoteReference' else 'endnote',n.get(W+'id'))]) for n in main.iter() if n.tag in (W+'footnoteReference',W+'endnoteReference')]
        sections={kind:[word_text(xml(z,n)) for n in z.namelist() if n.startswith('word/'+kind) and n.endswith('.xml')] for kind in ['header','footer']}
        core=xml(z,'docProps/core.xml')
        return dict(notes=notes,referenceOrder=reference_order,tableCount=len(main.findall('.//'+W+'tbl')),body=paragraphs(body,True),sections=sections,pictures=sorted(sha(z.read(n)) for n in z.namelist() if n.startswith('word/media/')),
                    metadata={key:core.findtext('dc:'+key,namespaces=ns) for key in ['title','creator']},comments=word_comments(z,main))
def output_features(path):
    with ZipFile(path) as z:
        assert z.read('mimetype')==b'application/vnd.oasis.opendocument.text'
        content=xml(z,'content.xml');styles=xml(z,'styles.xml');meta=xml(z,'meta.xml')
        notes=[dict(kind=n.get(T+'note-class'),id=n.get(T+'id'),text=norm(odf_inline(n.find(T+'note-body')))) for n in content.findall('.//'+T+'note')]
        body=content.find('.//{'+ns['office']+'}text')
        sections={kind:[norm(odf_inline(n)) for n in styles.findall('.//{'+ns['style']+'}'+kind)] for kind in ['header','footer']}
        return dict(notes=notes,tableCount=len(content.findall('.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table')),body=paragraphs(body),sections=sections,pictures=sorted(sha(z.read(n)) for n in z.namelist() if n.startswith('Pictures/') and not n.endswith('/')),
                    metadata={'title':meta.findtext('.//dc:title',namespaces=ns),'creator':meta.findtext('.//meta:initial-creator',namespaces=ns)},authorRole='initial-creator (original author), not last-modifier dc:creator',comments=odf_comments(content))

def word_comments(archive,main):
    if 'word/comments.xml' not in archive.namelist():return []
    definitions={node.get(W+'id'):dict(text=word_text(node),author=node.get(W+'author','')) for node in xml(archive,'word/comments.xml')}
    visible=[];starts={};ranges={};refs=[]
    def visit(node):
        tag=node.tag;identity=node.get(W+'id')
        if tag==W+'commentRangeStart':starts[identity]=len(''.join(visible))
        elif tag==W+'commentRangeEnd' and identity in starts:ranges[identity]=norm(''.join(visible)[starts[identity]:])
        elif tag==W+'commentReference':refs.append(identity)
        elif tag==W+'t':visible.append(node.text or '')
        elif tag in (W+'tab',W+'br',W+'cr'):visible.append(' ')
        else:
            for child in node:visit(child)
            if tag==W+'p':visible.append('\n')
    visit(main.find(W+'body'))
    return [dict(id=identity,scope='main',rangeText=ranges.get(identity),**definitions[identity]) for identity in dict.fromkeys(refs) if identity in definitions]

def odf_comments(content):
    O='{'+ns['office']+'}';visible=[];starts={};ranges={};items={}
    def visit(node):
        if node.tag==T+'note':return
        if node.tag==O+'annotation':
            name=node.get(O+'name');starts[name]=len(''.join(visible))
            items[name]=dict(id=name,scope='main',text=norm(''.join(odf_inline(p) for p in node.xpath('.//text:p | .//text:h',namespaces=ns))),author=node.findtext('dc:creator',default='',namespaces=ns));return
        if node.tag==O+'annotation-end':
            name=node.get(O+'name')
            if name in starts:ranges[name]=norm(''.join(visible)[starts[name]:])
            return
        if node.tag==T+'s':visible.append(' '*int(node.get(T+'c','1')));return
        if node.tag in (T+'tab',T+'line-break'):visible.append(' ');return
        visible.append(node.text or '')
        for child in node:visit(child);visible.append(child.tail or '')
        if node.tag in (T+'p',T+'h'):visible.append('\n')
    visit(content.find('.//'+O+'text'))
    return [dict(item,rangeText=ranges.get(name)) for name,item in items.items()]
