#!/usr/bin/python3
#
# Inject self-links into the Docbook-generated HTML pages.
#
# Run from the directory containing the HTML files.
#

import glob
import re

# The CSS and JS we want to inject
INJECTION = """
<style>
  .selflink { opacity: 0; margin-left: 8px; text-decoration: none; color: #4183c4; font-size: 0.8em; transition: 0.15s; }
  h1:hover .selflink, h2:hover .selflink, h3:hover .selflink, 
  h4:hover .selflink, h5:hover .selflink, dt:hover .selflink { opacity: 1; }
</style>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    // 1. Find every anchor tag that acts as a target name/ID
    document.querySelectorAll("a[name]").forEach(function(anchor) {
      if (!anchor.name) return;

      var targetElement = null;

      // Case 1: The anchor is nested inside a heading or DT (your previous format, or inside <DT>)
      // Example: <DT><A NAME="..."></A><B>text</B></DT>
      var parent = anchor.parentElement;
      if (parent && /^(H[1-5]|DT)$/i.test(parent.tagName)) {
        targetElement = parent;
      }

      // Case 2: The anchor is a sibling right before a heading
      // Example: <A NAME="..."></A><H3>Title</H3>
      if (!targetElement && anchor.nextElementSibling && /^(H[1-5])$/i.test(anchor.nextElementSibling.tagName)) {
        targetElement = anchor.nextElementSibling;
      }

      // 2. If we found a valid title/header container, append the selflink
      if (targetElement) {
        // Double-check to prevent duplicate links if elements are nested oddly
        if (targetElement.querySelector(".selflink")) return;

        var p = document.createElement("a");
        p.className = "selflink";
        p.href = "#" + anchor.name;
        p.innerHTML = "¶";
        p.title = "Link to this section";
        
        // If it's a DT, append to the bold text block if it exists, otherwise the DT itself
        var boldChild = targetElement.querySelector("b, strong");
        if (boldChild) {
          boldChild.appendChild(p);
        } else {
          targetElement.appendChild(p);
        }
      }
    });
  });
</script>
</HEAD
"""

# Find all HTML files generated by DocBook
for filepath in glob.glob("*.html"):
    print(f"=== Injecting selflinks in {filepath}...")
    with open(filepath, "r", encoding="utf-8", errors="ignore") as file:
        content = file.read()
        
    # Replace the closing HEAD tag with our payload (case-insensitive just in case)
    new_content = re.sub(r"(?i)</HEAD", INJECTION, content)
    
    with open(filepath, "w", encoding="utf-8") as file:
        file.write(new_content)
