#!/usr/bin/env python3
"""
Extract JavaScript from index.php and save to assets/js/app.js
"""

import re
import os

def extract_javascript():
    index_file = os.path.join(os.path.dirname(__file__), '..', 'index.php')
    output_file = os.path.join(os.path.dirname(__file__), '..', 'assets', 'js', 'app.js')
    
    if not os.path.exists(index_file):
        print(f"Error: {index_file} not found!")
        return
    
    with open(index_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Find JavaScript section (the last <script> tag before </body>)
    # Look for the main script tag that contains the app object
    start_tag = '<script>'
    end_tag = '</script>'
    
    # Find the last <script> tag (should be the main one)
    start_pos = content.rfind(start_tag)
    # Find the corresponding </script> tag
    end_pos = content.find(end_tag, start_pos)
    
    if start_pos == -1 or end_pos == -1:
        print("Error: JavaScript section not found!")
        return
    
    # Extract JavaScript (skip <script> tag itself)
    start_pos += len(start_tag)
    js_code = content[start_pos:end_pos]
    
    # Replace PHP code blocks with JavaScript equivalents
    replacements = [
        # Pattern 1: const APP_USER = <?php echo json_encode([...]); ?>;
        (r"const APP_USER = <\?php echo json_encode\(\[.*?\]\); \?>;",
         "// APP_USER will be defined in layout\nconst APP_USER = window.APP_USER || { role: 'guest', didar_id: null, name: '' };"),
        
        # Pattern 2: <?php echo $_SESSION['user_id'] ?? 0; ?>
        (r"<\?php echo \$_SESSION\['user_id'\] \?\? 0; \?>",
         "window.CURRENT_USER_ID || 0"),
        
        # Pattern 3: <?php echo ($_SESSION['role'] ?? '') === 'admin' ? 'true' : 'false'; ?>
        (r"<\?php echo \(\$_SESSION\['role'\] \?\? ''\) === 'admin' \? 'true' : 'false'; \?>",
         "(window.APP_USER?.role === 'admin') ? 'true' : 'false'"),
        
        # Pattern 4: <?php echo $_SESSION['role'] ?? ''; ?>
        (r"<\?php echo \$_SESSION\['role'\] \?\? ''; \?>",
         "window.APP_USER?.role || ''"),
        
        # Pattern 5: <?php echo addslashes($_SESSION['name'] ?? ''); ?>
        (r"<\?php echo addslashes\(\$_SESSION\['name'\] \?\? ''\); \?>",
         "(window.APP_USER?.name || '').replace(/'/g, \"\\\\'\")"),
        
        # Pattern 6: <?php if(isset($_SESSION['user_id'])): ?>
        (r"<\?php if\(isset\(\$_SESSION\['user_id'\]\)\): \?>",
         "if (window.APP_USER && window.CURRENT_USER_ID) {"),
        
        # Pattern 7: <?php if($_SESSION['role'] === 'admin'): ?>
        (r"<\?php if\(\$_SESSION\['role'\] === 'admin'\): \?>",
         "if (window.APP_USER?.role === 'admin') {"),
        
        # Pattern 8: <?php endif; ?>
        (r"<\?php endif; \?>",
         "}"),
        
        # Pattern 9: window.currentUserId || <?php echo $_SESSION['user_id'] ?? 0; ?>
        (r"window\.currentUserId \|\| <\?php echo \$_SESSION\['user_id'\] \?\? 0; \?>",
         "window.CURRENT_USER_ID || 0"),
    ]
    
    for pattern, replacement in replacements:
        js_code = re.sub(pattern, replacement, js_code, flags=re.DOTALL)
    
    # Clean up any remaining PHP tags
    js_code = re.sub(r'<\?php.*?\?>', '/* PHP code removed */', js_code, flags=re.DOTALL)
    
    # Add resumeSync function if missing
    if 'resumeSync' not in js_code:
        # Find where to add it (after setupSync)
        setup_sync_pos = js_code.find('async setupSync')
        if setup_sync_pos != -1:
            # Find the end of setupSync function
            brace_count = 0
            pos = setup_sync_pos
            in_function = False
            while pos < len(js_code):
                if js_code[pos] == '{':
                    brace_count += 1
                    in_function = True
                elif js_code[pos] == '}':
                    brace_count -= 1
                    if in_function and brace_count == 0:
                        # Add resumeSync after this closing brace
                        insert_pos = pos + 1
                        resume_sync_code = ''',
    
    async resumeSync() {
        try {
            const res = await this.req('resume_sync', {});
            if (res.status === 'success') {
                this.setupSync(res.step || 'users', res.from || 0);
            } else {
                Swal.fire('خطا', res.message || 'خطا در ادامه همگام‌سازی', 'error');
            }
        } catch (error) {
            console.error('Error in resumeSync:', error);
            Swal.fire('خطا', 'خطا در ادامه همگام‌سازی: ' + (error.message || 'خطای نامشخص'), 'error');
        }
    },'''
                        js_code = js_code[:insert_pos] + resume_sync_code + js_code[insert_pos:]
                        break
                pos += 1
    
    # Ensure directory exists
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    
    # Write to file
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(js_code)
    
    print(f"JavaScript extracted successfully to: {output_file}")
    print(f"Size: {len(js_code):,} bytes")
    print(f"Lines: {js_code.count(chr(10)) + 1}")

if __name__ == '__main__':
    extract_javascript()

