"""Retrieve public publication metadata from NCBI in one bounded request."""
import csv,json,pathlib,urllib.request,urllib.parse,datetime
root=pathlib.Path(__file__).resolve().parents[1]
with open(root/'data/derived/drugage_publication_means.csv') as f:ids=[r['pubmed_id'] for r in csv.DictReader(f)]
url='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?'+urllib.parse.urlencode({'db':'pubmed','id':','.join(ids),'retmode':'json'})
with urllib.request.urlopen(url,timeout=45) as r:body=r.read()
(root/'references/drugage_ncbi_metadata.json').write_bytes(body)
data=json.loads(body)['result'];out=[]
for i in ids:
 x=data.get(i,{})
 out.append(dict(source_key=i,title=x.get('title',''),authors='; '.join(a['name'] for a in x.get('authors',[])),journal=x.get('fulljournalname',''),date=x.get('pubdate',''),volume=x.get('volume',''),issue=x.get('issue',''),pages=x.get('pages',''),doi=next((a['value'] for a in x.get('articleids',[]) if a.get('idtype')=='doi'),''),url='https://pubmed.ncbi.nlm.nih.gov/'+i+'/',verification_note='Metadata retrieved; article-level data not fully re-extracted.'))
for x in out:
 if x['source_key']=='101039':
  x.update(title='UNRESOLVED SOURCE KEY: 2-SeCD lifespan records (numeric source link is mismatched)',authors='',journal='',date='',volume='',issue='',pages='',doi='',url='https://pubs.rsc.org/en/content/articlehtml/2017/ra/c7ra07210d',verification_note='NCBI 101039 resolves to an unrelated radiology article. URL is a candidate relevant 2-SeCD paper; exact extraction not verified. Exclusion sensitivity supplied. Raw NCBI metadata preserved separately.')
with open(root/'references/drugage_bibliography.csv','w',newline='') as f:
 w=csv.DictWriter(f,fieldnames=out[0].keys());w.writeheader();w.writerows(out)
print('Metadata records',len(out),'missing titles',sum(not x['title'] for x in out))
