from pathlib import Path
import subprocess,json,re,tarfile,sys,runpy,hashlib
m=runpy.run_path('/tmp/lead-29548-r1/evidence-capture-2/public-manifest.py');r=m['ROOT']
if len(sys.argv)>1:names=sys.argv[1:]
else:
 names=m['ASSETS']+m['SCRIPTS']+m['DATA']
 with tarfile.open(r/'evidence-sources.tar.gz','w:gz') as tar:
  for name in names+m['WITNESSES']:
   p=r/name
   if not p.is_file():raise RuntimeError('Missing public artifact '+name)
   if p.suffix in ['.js','.py','.sh','.md','.json','.jsonl']:
    text=p.read_text()
    if re.search(r'Bearer\s+[A-Za-z0-9_-]{12,}|pair#token=[A-Za-z0-9_-]{12,}',text):raise RuntimeError('Credential-shaped content '+name)
   tar.add(p,arcname=name)
 names+=['evidence-sources.tar.gz']
mapPath=r/'upload-map.json';mapping=json.loads(mapPath.read_text()) if mapPath.exists() else {}
for name in names:
 p=r/name
 digest=hashlib.sha256(p.read_bytes()).hexdigest()
 if name in mapping and mapping[name].get('sha256')==digest:continue
 if p.parent!=r or not p.is_file():raise RuntimeError('Public upload allowlist contains invalid root file '+name)
 result=subprocess.run(['ghdrop','upload','-m',str(p)],capture_output=True,text=True)
 if result.returncode:print(result.stderr,flush=True);raise SystemExit(result.returncode)
 # Preserve ghdrop stdout exactly, including its original newline.
 with (r/'ghdrop-output.md').open('a') as f:f.write(result.stdout)
 print(result.stdout,end='',flush=True)
 match=re.search(r'\((https://[^)]+)\)',result.stdout)
 if not match:raise RuntimeError(result.stdout)
 mapping[name]={'markdown':result.stdout.strip(),'url':match.group(1),'sha256':digest}
 mapPath.write_text(json.dumps(mapping,indent=2))
print('Uploaded public artifacts:',len(mapping),flush=True)
