"""Authenticated draft readback, byte checks, audit and history; no content writes."""
import os,sys,json,hashlib,urllib.request
from pathlib import Path
sys.path.insert(0,str(Path.cwd()))
from agents.argument_review import Website,selection_fingerprint
from agents.scientific_review import capture,presentation_findings,metadata
class Site(Website):
 def __init__(self):
  self.key=sys.stdin.read().strip();assert self.key and not any(c.isspace() for c in self.key)
  self.host='https://numberdb.org';self.proxy=None
w=Path(os.environ['TMPDIR']);site=Site();snap,doc=capture(site,'T725');meta=metadata(site,'T725')
assert meta['status']=='in_progress' and meta['created_by']=='zeta3'
expected=json.loads((w/'document.json').read_text())
# The API canonicalizes Data properties.digits to a string.
expected['Data properties']['digits']=str(expected['Data properties']['digits'])
assert len(doc['Numbers'])==12 and doc==expected
assert doc==json.loads((w/'stored-table.json').read_text())
findings=presentation_findings(doc);assert not findings
files=[]
for name,expected in snap['files'].items():
 local=w/name;assert local.is_file(),name
 content=site.get('files/T725/'+name+'?raw=1');digest=hashlib.sha256(content).hexdigest()
 assert digest==expected==hashlib.sha256(local.read_bytes()).hexdigest(),name
 files.append({'name':name,'sha256':digest,'bytes':len(content),'matches_local':True})
assert capture(site,'T725')[0]==snap,'Concurrent change during attachment checking'
(w/'final-snapshot.json').write_text(json.dumps(snap,indent=2));(w/'metadata-final.json').write_text(json.dumps(meta,indent=2));(w/'stored-table-final.json').write_text(json.dumps(doc,ensure_ascii=False,indent=2))
audit=json.loads(site.get('api/table/T725/audit'));(w/'audit-final.json').write_text(json.dumps(audit,indent=2))
(w/'attachments-check.json').write_text(json.dumps({'table':'T725','checked_files':len(files),'files':files,'presentation_findings':findings},indent=2))
body=urllib.request.urlopen('https://numberdb.org/revisions/T725',timeout=60).read();(w/'revisions-final.html').write_bytes(body);text=body.decode()
checks={s:s in text for s in ['https://github.com/numberdb/numberdb-data/issues/323','https://github.com/numberdb/numberdb-data/issues/263','codex-cli','gpt-6.1-sol']};assert all(checks.values())
(w/'history-check.json').write_text(json.dumps({'source':'revisions-final.html','preserved':checks},indent=2))
selection={'table':'T725','selection_sha256':selection_fingerprint(doc),'generator_files':{'generate.py':snap['files']['generate.py']},'note':'Fingerprint only; not an independent argument assessment.'}
(w/'selection-fingerprint.json').write_text(json.dumps(selection,indent=2))
print(json.dumps({'table':'T725','status':meta['status'],'revision':snap['revision'],'checked_files':len(files),'history_citations_preserved':True,'presentation_findings':findings}))
