from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile,ZIP_DEFLATED
from pypdf import PdfReader
import subprocess,json,hashlib
p=Path(__file__).resolve().parent
w='http://schemas.openxmlformats.org/wordprocessingml/2006/main';r='http://schemas.openxmlformats.org/officeDocument/2006/relationships';pkg='http://schemas.openxmlformats.org/package/2006/relationships'
def text(t,blue=False):
 fmt='<w:rPr><w:color w:val="0000FF"/><w:u w:val="single"/></w:rPr>' if blue else ''
 return '<w:r>'+fmt+'<w:t>'+t+'</w:t></w:r>'
para=lambda s:'<w:p>'+s+'</w:p>'
doc='<w:document xmlns:w="'+w+'" xmlns:r="'+r+'"><w:body>'+''.join([
 para(text('Three labels to test after export')),
 para('<w:hyperlink w:anchor="ActivityTable">'+text('Open the activity table',True)+'</w:hyperlink>'),
 para('<w:hyperlink r:id="rExternal">'+text('Open the example website',True)+'</w:hyperlink>'),
 para(text('Blue text without a link',True)),para('<w:r><w:br w:type="page"/></w:r>'),
 para('<w:bookmarkStart w:id="3" w:name="ActivityTable"/>'+text('Activity table — destination')+'<w:bookmarkEnd w:id="3"/>')])+ '<w:sectPr/></w:body></w:document>'
rels=lambda items:'<Relationships xmlns="'+pkg+'">'+items+'</Relationships>'
body={'[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"/></Types>','_rels/.rels':rels('<Relationship Id="rMain" Type="'+r+'/officeDocument" Target="word/document.xml"/>'),'word/_rels/document.xml.rels':rels('<Relationship Id="rExternal" Type="'+r+'/hyperlink" Target="https://example.org/" TargetMode="External"/>'),'word/document.xml':doc}
f=p/'link-control.docx'
with ZipFile(f,'w',compression=ZIP_DEFLATED) as z:
 for n,v in body.items():z.writestr(n,v.encode('utf-8'))
with TemporaryDirectory() as tmp:
 subprocess.run(['/usr/bin/libreoffice','-env:UserInstallation='+Path(tmp).as_uri(),'--headless','--convert-to','pdf','--outdir',str(p),str(f)],check=True,capture_output=True,timeout=65)
out=p/'link-control.pdf';d=PdfReader(out);observed=[]
for pi,page in enumerate(d.pages,1):
 for ref in page.get('/Annots',[]):
  an=ref.get_object();dest=an.get('/Dest');act=an.get('/A',{});dest=dest or act.get('/D')
  if isinstance(dest,(str,bytes)): dest=d.named_destinations.get(str(dest))
  ix=None
  if dest and isinstance(dest,list):ix=next((i for i,pg in enumerate(d.pages,1) if pg.indirect_reference==dest[0]),None)
  elif dest is not None and hasattr(dest,'page'):ix=d.get_destination_page_number(dest)+1
  observed.append({'page':pi,'type':str(an.get('/Subtype')),'uri':act.get('/URI'),'internal_page':ix,'bounds':list(an.get('/Rect',[]))})
assert len(d.pages)==2 and len(observed)==2 and any(a['uri']=='https://example.org/' for a in observed) and any(a['internal_page']==2 for a in observed)
data={'scope':'Local DOCX fixture exported by LibreOffice, not Microsoft Word; PDF link annotations inspected with pypdf. No external site contacted in this test.','exporter':subprocess.run(['/usr/bin/libreoffice','--version'],capture_output=True,text=True).stdout.strip(),'docx_sha256':hashlib.sha256(f.read_bytes()).hexdigest(),'pdf_sha256':hashlib.sha256(out.read_bytes()).hexdigest(),'pages':len(d.pages),'observed_annotations':observed,'source_labels':['Open the activity table','Open the example website','Blue text without a link']}
(p/'observations.json').write_text(json.dumps(data,indent=2)+'\n');print(data['observed_annotations'])
