import re
from pathlib import Path

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

# 1) Make docx-content visible inline (remove hidden) and add class
text = text.replace('class="docx-content" hidden', 'class="docx-content docx-inline"')

# 2) Add per-exhibit back button next to view link if missing
if 'doc-back-inline' not in text:
    text = re.sub(
        r'(\<a class="doc-link doc-open"[^>]*>[^<]*</a>)',
        r"\1\n        <button class=\"doc-back-inline\" type=\"button\">Back to where you were</button>",
        text
    )

# 3) Fix modal script: add inline back handler and scroll restore
if 'doc-back-inline' not in text:
    pass

# Ensure lastScrollY exists
if 'let lastScrollY' not in text:
    text = text.replace("const modal = document.getElementById('doc-modal');", "const modal = document.getElementById('doc-modal');\n  let lastScrollY = 0;")

# Ensure openModal stores scroll
if 'lastScrollY = window.scrollY' not in text:
    text = text.replace('function openModal(title, contentHtml) {', 'function openModal(title, contentHtml) {\n    lastScrollY = window.scrollY || 0;')

# Ensure closeModal restores scroll with auto
if 'window.scrollTo' not in text:
    text = text.replace("document.body.classList.remove('modal-open');", "document.body.classList.remove('modal-open');\n    window.scrollTo({ top: lastScrollY, behavior: 'auto' });")
else:
    text = text.replace("behavior: 'instant'", "behavior: 'auto'")

# Add inline back handler and ensure modal back handler exists
if 'doc-back-inline' not in text:
    pass

if 'doc-back-inline' not in text and 'data-back' not in text:
    pass

# Inject inline back handler in click listener
if 'doc-back-inline' in text and 'const backInline' not in text:
    text = text.replace(
        "const close = e.target.closest('[data-close=\"true\"]');",
        "const close = e.target.closest('[data-close=\"true\"]');\n    const backInline = e.target.closest('.doc-back-inline');\n    if (backInline) {\n      e.preventDefault();\n      window.scrollTo({ top: lastScrollY, behavior: 'auto' });\n      return;\n    }"
    )

path.write_text(text, encoding='utf-8')
print('updated inline docx visibility and back buttons')
