from pathlib import Path
import subprocess, shutil, json, re

root=Path('/tmp/issue-lead-26950-r1/evidence-capture')
out=root/'deliverables'
scripts=['seed.sh','start-servers.py','instrument.js','harness.js','driver.js','package-evidence.py','upload-evidence.py','build-index.py','reproduce.md','fixture-matrix.md']
for name in scripts:
    shutil.copy2(root/name,out/name)
files=[p for p in sorted(out.iterdir()) if p.is_file() and '-video-frame-' not in p.name and p.name not in ('index.md','uploads.md','upload-map.json')]
for p in files:
    if p.suffix in ('.json','.js','.py','.sh','.md'):
        text=p.read_text()
        if re.search(r'(?:pairingToken|authToken|sessionToken)\s*[=:]\s*[\"\'][A-Za-z0-9_-]{20}',text):
            raise RuntimeError('Potential secret: '+p.name)
result=subprocess.run(['ghdrop','upload','-m',*[str(p) for p in files]],text=True,capture_output=True,check=True)
(root/'uploads.md').write_text(result.stdout)
(out/'uploads.md').write_text(result.stdout)
mapping={}
for line in result.stdout.splitlines():
    match=re.fullmatch(r'!?\[([^]]+)\]\((https://[^)]+)\)',line.strip())
    if match: mapping[match[1]]={'markdown':line,'url':match[2]}
if len(mapping)!=len(files):
    raise RuntimeError(f'Upload manifest mismatch: {len(mapping)} URLs for {len(files)} files')
(root/'upload-map.json').write_text(json.dumps(mapping,indent=2))
print(result.stdout,end='')
