"""Publish the final index and Markdown after immutable asset URLs exist."""
from pathlib import Path
import json,re,subprocess,zipfile
root=Path('/tmp/lead-25709-r1b/evidence-capture');mapping=json.loads((root/'uploaded-assets.json').read_text());log=root/'uploads-publish.md'
if not log.exists():log.write_text('')
def upload(files):
 result=subprocess.run(['ghdrop','upload','-m',*[str(p)for p in files]],capture_output=True,text=True,check=True)
 with log.open('a')as f:f.write(result.stdout)
 links=re.findall(r'!?\[[^\]]*\]\((https://[^)]+)\)',result.stdout);assert len(links)==len(files)
 mapping.update(zip(map(str,files),links));(root/'uploaded-assets.json').write_text(json.dumps(mapping,indent=2));return result.stdout
with zipfile.ZipFile(root/'evidence-scripts.zip','w',zipfile.ZIP_DEFLATED)as z:
 for p in root.iterdir():
  if p.suffix in ['.cjs','.py','.sh']or p.name=='REPRODUCE.md':z.write(p,p.name)
upload([root/'build-evidence.py',root/'sheets.py',root/'REPRODUCE.md',root/'publish.py',root/'evidence-scripts.zip',root/'sheets/before-after-secrets-page.png'])
subprocess.run(['python3',str(root/'build-evidence.py')],check=True)
print(upload([root/'index.html']),end='',flush=True)
subprocess.run(['python3',str(root/'build-evidence.py')],check=True)
print(upload([root/'evidence.md']),end='',flush=True)
(root/'uploads.md').write_text((root/'uploads-assets.md').read_text()+log.read_text())
print(upload([root/'uploads.md']),end='',flush=True)
# The final handoff quotes selected original ghdrop lines; the complete output is public above.
all_output=(root/'uploads-assets.md').read_text()+log.read_text()
names=['index.html','evidence.md','uploads.md','capture.cjs','seed-project.sh','evidence-scripts.zip','REPRODUCE.md','secrets-settings-R0-R12-overview']
selected=[]
for line in all_output.splitlines():
 label=re.match(r'!?\[([^]]+)\]',line)
 if label and (label[1] in names or label[1].startswith(('01-','02-','03-','04-','05-','06-'))):selected.append(line)
(root/'final-links.md').write_text('\n'.join(dict.fromkeys(selected))+'\n')
