#!/usr/bin/env python3
"""
DecentraBrowser Syntax Error Fix

This script fixes the syntax error in main_window.py
around line 1442 where there's an incomplete try-except block.

Usage:
    python syntax_error_fix.py
"""

import os
import sys
import shutil
import re

def backup_file(file_path):
    """Create a backup of a file before modifying it."""
    backup_path = file_path + '.syntax.bak'
    print(f"Creating backup: {backup_path}")
    shutil.copy2(file_path, backup_path)
    return backup_path

def fix_syntax_error(main_window_py):
    """Fix the syntax error in main_window.py."""
    with open(main_window_py, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # Find the incomplete try block around line 1442
    line_number = None
    for i, line in enumerate(lines):
        if "self.refresh_domains()" in line:
            # Look backward to find the corresponding try
            j = i
            while j >= 0:
                if "try:" in lines[j] and i - j < 20:  # Within reasonable distance
                    # Check if there's an 'except' after the refresh_domains line
                    has_except = False
                    for k in range(i+1, min(i+10, len(lines))):
                        if "except" in lines[k]:
                            has_except = True
                            break
                    
                    if not has_except:
                        line_number = i
                        break
                j -= 1
            
            if line_number is not None:
                break
    
    if line_number is None:
        print("Could not find the line with the syntax error")
        return False
    
    # Fix the syntax error by adding an except block
    lines[line_number] = lines[line_number] + "        except Exception as e:\n            print(f\"Error refreshing domains: {str(e)}\")\n"
    
    # Write the fixed content
    with open(main_window_py, 'w', encoding='utf-8') as f:
        f.writelines(lines)
    
    print(f"Fixed syntax error around line {line_number+1} in {main_window_py}")
    return True

def fix_syntax_error_alternative(main_window_py):
    """Alternative approach to fix the syntax error by examining the entire file."""
    with open(main_window_py, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Look for patterns like "try:\n...\nself.refresh_domains()" without a corresponding except
    pattern = r'try:\s*.*?self\.refresh_domains\(\)(?!\s*except)'
    match = re.search(pattern, content, re.DOTALL)
    
    if not match:
        print("Could not find the syntax error pattern")
        return False
    
    error_code = match.group(0)
    fixed_code = error_code + "\n        except Exception as e:\n            print(f\"Error refreshing domains: {str(e)}\")"
    
    # Replace the erroneous code
    updated_content = content.replace(error_code, fixed_code)
    
    # Double-check for other incomplete try blocks
    try_blocks = re.findall(r'try:.*?(?=except|\Z)', updated_content, re.DOTALL)
    for block in try_blocks:
        if block.count('\n') > 2 and 'except' not in block and 'finally' not in block:
            # This is a suspicious block that might be incomplete
            print(f"Found another potentially incomplete try block:\n{block[:100]}...")
    
    # Write the fixed content
    with open(main_window_py, 'w', encoding='utf-8') as f:
        f.write(updated_content)
    
    print(f"Fixed syntax error in {main_window_py}")
    return True

def full_file_check_and_fix(main_window_py):
    """Last resort approach - do a complete file check and rewrite."""
    with open(main_window_py, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # Track open try blocks
    open_tries = []
    fixed = False
    
    for i, line in enumerate(lines):
        stripped = line.strip()
        
        # Track try blocks
        if stripped == "try:":
            open_tries.append(i)
        elif stripped.startswith("except") or stripped.startswith("finally:"):
            if open_tries:
                open_tries.pop()
        
        # If we're at the end of a code block and there are still open tries
        if stripped == "" and open_tries:
            # Add an except block after the last statement in the try block
            j = i - 1
            indentation = re.match(r'^(\s*)', lines[open_tries[-1]]).group(1)
            
            # Insert except block
            lines.insert(i, indentation + "except Exception as e:\n")
            lines.insert(i+1, indentation + "    print(f\"Error in try block: {str(e)}\")\n")
            
            # Adjust indices
            i += 2
            fixed = True
            open_tries.pop()
    
    # Write the fixed content
    if fixed:
        with open(main_window_py, 'w', encoding='utf-8') as f:
            f.writelines(lines)
        
        print(f"Fixed incomplete try blocks in {main_window_py}")
        return True
    else:
        print("No incomplete try blocks found")
        return False

def main():
    """Main function."""
    # Find DecentraBrowser installation directory
    base_dir = None
    possible_paths = [
        os.path.join(".", "decentrabrowser"),
        os.path.join("..", "decentrabrowser"),
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "decentrabrowser")
    ]
    
    for path in possible_paths:
        if os.path.isdir(path):
            base_dir = path
            break
    
    if not base_dir:
        print("Error: Could not find DecentraBrowser directory.")
        print("Please run this script from the same directory as the 'decentrabrowser' folder.")
        return 1
    
    print(f"Found DecentraBrowser at: {base_dir}")
    
    # Target file
    main_window_py = os.path.join(base_dir, "client", "gui", "main_window.py")
    
    if not os.path.exists(main_window_py):
        print(f"Error: {main_window_py} not found.")
        return 1
    
    # Create backup
    backup_file(main_window_py)
    
    # Try to fix the syntax error using multiple approaches
    try:
        # First attempt - line by line search
        if fix_syntax_error(main_window_py):
            print("Syntax error fixed successfully using line search method.")
        # Second attempt - regex pattern
        elif fix_syntax_error_alternative(main_window_py):
            print("Syntax error fixed successfully using regex pattern method.")
        # Third attempt - full file check
        elif full_file_check_and_fix(main_window_py):
            print("Syntax error fixed successfully using full file check method.")
        else:
            print("All fix attempts failed. Manual intervention may be required.")
            return 1
    except Exception as e:
        print(f"Error while fixing syntax error: {str(e)}")
        return 1
    
    print("\nSyntax error fix applied successfully!")
    print("Please restart DecentraBrowser to apply the changes.")
    
    return 0

if __name__ == "__main__":
    sys.exit(main())
