"""Local stored-record lookup plus read-only authenticated API controls.

Run in the campaign work directory with NUMBERDB_WORKDIR set. The API key is
read from NUMBERDB_KEY_FILE and sent only to numberdb.org. Local matches are
not a claim that the private draft is available in public number search.
"""
import pathlib,os,sys,json,urllib.request,urllib.parse
w=pathlib.Path(os.environ['NUMBERDB_WORKDIR']);root=pathlib.Path.cwd();sys.path.insert(0,str(root));sys.path.insert(0,str(w))
from agents.api_edit import read_key,use_socks_proxy_if_set
from independent_check import unpack
use_socks_proxy_if_set();key=read_key();tid=json.loads((w/'draft-created.json').read_text())['tid']
def get(path):
 with urllib.request.urlopen(urllib.request.Request('https://numberdb.org/'+path,headers={'Authorization':'Bearer '+key}),timeout=60) as r:return json.load(r)
metadata=get('api/table/'+tid+'/metadata');base=metadata['url'];rows=unpack(json.loads((w/'stored-document.json').read_text()));local=[];public=[]
for params,u,p,n in rows:
 if p!=59:continue
 for qn in [n,12]:
  residue=u%(p**qn);matches=[]
  for other,v,prime,prec in rows:
   if prime==p and prec>=qn and (v-residue)%(p**qn)==0:
    matches.append({'table':tid,'entry_url':base+'#'+','.join(str(other[k]) for k in ['p','k','a']),'params':other,'polynomial':'x^3-x-1','definition_url':base})
  assert any(m['params']==params for m in matches)
  query={'kind':'Qp','prime':p,'valuation':0,'unit':str(residue),'precision':qn}
  local.append({'query':query,'matches':matches,'scope':'local stored records'})
  response=get('api/lookup?'+urllib.parse.urlencode({'number':json.dumps(query)}));assert 'error' not in response,response
  assert tid not in json.dumps(response),'unexpected private draft public search result'
  public.append({'query':query,'response':response,'expected_private_table':tid,'private_table_withheld':True})
(w/'lookup-local.json').write_text(json.dumps({'table':tid,'dictionary':{'x^3-x-1':{'meaning':'exact plastic-constant polynomial; branch params are p,k,a','definition_url':base,'primary_source':'https://repository.essex.ac.uk/13403/'}},'queries':local},indent=2)+'\n')
(w/'lookup-public-private.json').write_text(json.dumps(public,indent=2)+'\n');print('Local full/short queries:',len(local),'all return their exact branch. API private withholding:',len(public))
