"""Score a Word file converted from one of the Arabic test PDFs.
Usage: python3 -I check-docx.py <source.pdf name> <file.docx> [...]
Checks: real Arabic letters (no presentation-form code points), every line found
as written (in reading order), words found."""
import sys,zipfile,re,json,os
cases=json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)),'cases.json')))
src=sys.argv[1]; TRUE=next(f['lines'] for f in cases['files'] if f['file']==src)
def paras(p):
    x=zipfile.ZipFile(p).read('word/document.xml').decode('utf-8')
    out=[]
    for para in re.findall(r'<w:p[ >].*?</w:p>',x,re.S):
        t=''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>',para))
        if t.strip(): out.append(t)
    return out
sp=lambda s: re.sub(r'\s+',' ',s).strip()
for f in sys.argv[2:]:
    ps=paras(f); text=sp(' '.join(ps))
    pres=len(re.findall(r'[ﭐ-﷿ﹰ-﻿]',text))
    words=[w for l in TRUE for w in l.split()]
    found=sum(1 for w in words if re.search(r'(?<!\S)'+re.escape(w)+r'(?!\S)',text))
    lines=sum(1 for l in TRUE if sp(l) in text)
    rev=sum(1 for l in TRUE if len(l.split())>1 and ' '.join(reversed(sp(l).split())) in text)
    print(json.dumps({"file":os.path.basename(f),"source":src,"lines_as_written":f"{lines}/{len(TRUE)}","words_found":f"{found}/{len(words)}","letter_shape_codes":pres,"reversed_lines":rev,"sample":ps[:3]},ensure_ascii=False))
