import re
from pathlib import Path

index_path = Path(r'd:\kreuzberg\pipeline_claim\index.html')
text = index_path.read_text(encoding='utf-8', errors='replace')

# Inject fileParam logic after contentHtml init
pattern = re.compile(r'(const embed = card.querySelector\(\'.doc-embed\'\);[\s\S]*?let contentHtml = embed \? embed.innerHTML : \'<p>No preview available\.\</p>\';)', re.MULTILINE)

if 'fileParam' not in text:
    def repl(match):
        block = match.group(1)
        inject = """
    const linkTarget = link.getAttribute('data-file') || '';
    let fileParam = '';
    if (linkTarget.includes('doc_viewer.html?file=')) {
      fileParam = linkTarget.split('doc_viewer.html?file=')[1];
      if (fileParam.includes('&page=')) {
        fileParam = fileParam.split('&page=')[0];
      }
    }

    if (fileParam) {
      const ext = fileParam.split('.').pop().toLowerCase();
      if (ext === 'pdf') {
        contentHtml = `<object data="${fileParam}" type="application/pdf" width="100%" height="720"></object>`;
      } else if (['jpg','jpeg','png','gif','webp'].includes(ext)) {
        contentHtml = `<img src="${fileParam}" alt="Document image" />`;
      }
    }
"""
        return block + inject
    text = pattern.sub(repl, text, count=1)

index_path.write_text(text, encoding='utf-8')
print('updated modal script for fileParam rendering')
