#!/usr/bin/env python3
"""
Fix JavaScript by properly escaping newlines in the string
"""

import os
import re
import json

# Read guide.md
with open('guide.md', 'r', encoding='utf-8') as f:
    guide_content = f.read()

# Extract prompts
def extract_prompt_content(num):
    """Extract the full prompt text for a specific number"""

    # Pattern: Find "N. Title" and everything until next "M. Title" or end of file
    pattern = rf'^{num}\. .+?(?=^\d+\. |^## \d+\. |\Z)'
    match = re.search(pattern, guide_content, re.MULTILINE | re.DOTALL)

    if match:
        content = match.group(0).strip()
        content = re.sub(r'\n{3,}', '\n\n', content)
        if len(content) > 3500:
            content = content[:3500] + "\n\n... (내용이 길어 일부만 표시됩니다)"
        return content

    # Try ## format (for sections 93+)
    pattern2 = rf'^## {num}\. .+?(?=^## \d+\. |\Z)'
    match = re.search(pattern2, guide_content, re.MULTILINE | re.DOTALL)

    if match:
        content = match.group(0).strip()
        content = re.sub(r'\n{3,}', '\n\n', content)
        if len(content) > 3500:
            content = content[:3500] + "\n\n... (내용이 길어 일부만 표시됩니다)"
        return content

    return f"{num}번 프롬프트를 찾을 수 없습니다."

# Process each HTML file
success_count = 0
for i in range(1, 101):
    filename = f"{i:02d}.html"

    if not os.path.exists(filename):
        print(f"❌ Skipping {filename} - does not exist")
        continue

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

    # Extract the actual prompt for this number
    prompt_text = extract_prompt_content(i)

    # Use json.dumps to properly escape the string for JavaScript
    # json.dumps will handle all special characters correctly
    prompt_escaped = json.dumps(prompt_text, ensure_ascii=False)[1:-1]  # Remove surrounding quotes

    # Find the entire openPromptModal function and replace it
    pattern = r'function openPromptModal\(\) \{[\s\S]+?\n\}'

    # New function content - use triple quotes and format string
    new_function = '''function openPromptModal() {
    const modal = document.getElementById('promptModal');
    const promptText = document.getElementById('promptText');
    promptText.textContent = `''' + prompt_escaped + '''`;
    modal.classList.add('active');
    document.body.style.overflow = 'hidden';
}'''

    new_content = re.sub(pattern, new_function, content)

    if new_content != content:
        # Write back
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print(f"✓ Updated {filename}")
        success_count += 1
    else:
        print(f"⚠ No change in {filename}")

print(f"\n✅ Done! Successfully updated {success_count}/100 pages.")
print("JavaScript 에러가 모두 수정되었습니다!")
