#!/usr/bin/env python3
import re
import glob

# Proper CSS for prompt button
PROMPT_BTN_CSS = """        .prompt-btn {
            position: fixed;
            top: 20px;
            left: 180px;
            padding: 12px 24px;
            background: white;
            border-radius: 8px;
            border: 2px solid #667eea;
            color: #667eea;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            z-index: 100;
            transition: all 200ms ease;
        }"""

MOBILE_PROMPT_BTN_CSS = """        .prompt-btn {
            left: auto;
            right: 20px;
        }"""

def fix_html_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()

    # Remove the malformed .prompt-btn block after the second <style> tag
    # Find the pattern: .prompt-btn { ... } including all the malformed content
    content = re.sub(
        r'\.prompt-btn\s*\{[^}]*position:\s*fixed;[^}]*position:\s*fixed;[^}]*\}',
        '',
        content,
        flags=re.DOTALL
    )

    # Remove any remaining standalone .prompt-btn blocks in the second style section
    # This handles cases where the regex didn't catch everything
    content = re.sub(
        r'\.prompt-btn\s*\{[^}]*?\}',
        '',
        content,
        flags=re.DOTALL,
        count=10  # Remove up to 10 occurrences to clean up duplicates
    )

    # Now add the proper .prompt-btn CSS right after the opening of the second <style> tag
    # Find: <style>\n followed by whitespace and possible other content
    # Insert after the <style> tag
    pattern = r'(<style>\s*)'
    replacement = r'\1\n' + PROMPT_BTN_CSS + '\n\n'

    # Only replace the second <style> tag (the one after <section>)
    matches = list(re.finditer(pattern, content))
    if len(matches) >= 2:
        second_match = matches[1]
        content = content[:second_match.end()] + '\n' + PROMPT_BTN_CSS + '\n\n' + content[second_match.end():]

    # Now fix the mobile media query - remove any .prompt-btn blocks in mobile section
    # and add the proper one
    mobile_pattern = r'(@media\s*\([^)]*max-width:\s*768px[^)]*\)\s*\{)'

    def replace_mobile(match):
        media_start = match.group(0)
        # Find the end of this media query
        start_pos = match.end()
        brace_count = 1
        pos = start_pos

        while pos < len(content) and brace_count > 0:
            if content[pos] == '{':
                brace_count += 1
            elif content[pos] == '}':
                brace_count -= 1
            pos += 1

        media_content = content[start_pos:pos-1]

        # Remove all .prompt-btn blocks from this media query
        media_content = re.sub(
            r'\.prompt-btn\s*\{[^}]*?\}',
            '',
            media_content,
            flags=re.DOTALL
        )

        # Add the proper mobile .prompt-btn CSS
        media_content = '\n' + MOBILE_PROMPT_BTN_CSS + '\n' + media_content

        return media_start + media_content + '\n    }'

    # This is getting too complex. Let me use a simpler approach:
    # Find the mobile media query and replace just the .prompt-btn part

    # Simpler approach: find and replace within the mobile media query section
    # Pattern: find text between @media (max-width: 768px) { and the next }

    mobile_section_pattern = r'(@media\s*\([^)]*max-width:\s*768px[^)]*\)\s*\{)(.*?)(\n\s*\})'

    def fix_mobile_section(match):
        media_open = match.group(1)
        media_body = match.group(2)
        media_close = match.group(3)

        # Remove all .prompt-btn blocks from mobile section
        media_body = re.sub(
            r'\s*\.prompt-btn\s*\{[^}]*?\}',
            '',
            media_body,
            flags=re.DOTALL
        )

        # Add proper mobile .prompt-btn at the start of media body
        media_body = '\n' + MOBILE_PROMPT_BTN_CSS + media_body

        return media_open + media_body + media_close

    content = re.sub(mobile_section_pattern, fix_mobile_section, content, flags=re.DOTALL)

    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)

    print(f"Fixed: {filepath}")

# Process all HTML files
html_files = sorted(glob.glob('*.html'))
html_files = [f for f in html_files if f != 'index.html']

for html_file in html_files:
    try:
        fix_html_file(html_file)
    except Exception as e:
        print(f"Error processing {html_file}: {e}")

print(f"\nProcessed {len(html_files)} files")
