import re

def optimize_singlefile(input_file='ken_google_ngram_viewer_05032026_23203_AM-PST.html', output_file='ken_ngram_fixed_interactive.html'):
    print("Reading SingleFile export...")
    
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            content = f.read()
    except FileNotFoundError:
        print(f"Error: Could not find {input_file}. Ensure the filename matches perfectly.")
        return

    print("Injecting DOM cloaking and layout correction CSS...")
    
    cloaking_css = """
<style>
    /* 1. ANNIHILATE GOOGLE UI BLOAT SAFELY */
    .header, #search-field, #form-nav, #warning-area, #warnings, 
    #datasets-announcement, #books-table, #documentation, #about, 
    #social-media-section, #overflow-container, .footer-left, .footer-right {
        display: none !important;
        opacity: 0 !important;
        pointer-events: none !important;
    }

    /* 2. ISOLATE AND RESPONSIVELY CENTER THE CHART */
    body, html {
        margin: 0 !important;
        padding: 0 !important;
        background: #eceff1 !important;
        display: flex !important;
        justify-content: center !important;
        align-items: center !important;
        height: 100vh !important;
        width: 100vw !important;
        overflow: hidden !important;
    }

    #chart-parent {
        width: 95vw !important;
        max-width: 1400px !important;
        height: 85vh !important;
        margin: 0 !important;
        padding: 25px 30px !important;
        background: #ffffff !important;
        box-shadow: 0 8px 30px rgba(0,0,0,0.06) !important;
        border-radius: 12px !important;
        position: relative !important;
    }
    
    /* 3. FIX DUPLICATE GRAPH BUG */
    /* Remove display: flex to prevent side-by-side rendering */
    #chart {
        width: 100% !important;
        height: 100% !important;
        position: relative !important;
        display: block !important; 
    }

    /* Force all SVGs into the exact same absolute space */
    #chart > svg {
        position: absolute !important;
        top: 0 !important;
        left: 0 !important;
        width: 100% !important;
        height: 100% !important;
    }
    
    /* Hide the 'dead' static SVG captured by SingleFile. 
       Only display the final SVG appended by the JS engine. */
    #chart > svg:not(:last-child) {
        display: none !important;
        opacity: 0 !important;
        pointer-events: none !important;
        z-index: -1 !important;
    }
</style>
"""

    if '</head>' in content:
        optimized_content = content.replace('</head>', cloaking_css + '\n</head>')
    else:
        optimized_content = cloaking_css + content

    print("Writing optimized self-contained widget...")
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(optimized_content)

    print(f"Success! Saved pure interactive replica to {output_file}")

if __name__ == "__main__":
    optimize_singlefile()