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

This script fixes the syntax error in main_window.py that
occurred during the enhancement process.

Usage:
    python decentra_fix_error.py
"""

import os
import sys
import shutil

def fix_main_window(main_window_path):
    """Fix the syntax error in main_window.py."""
    print(f"Fixing {main_window_path}...")
    
    # Check if backup exists
    backup_path = main_window_path + '.bak'
    if os.path.exists(backup_path):
        print(f"Restoring from backup: {backup_path}")
        shutil.copy2(backup_path, main_window_path)
        print("Successfully restored from backup.")
        return True
    
    print("No backup found. Attempting manual fix...")
    
    # If no backup exists, try to fix the file directly
    with open(main_window_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Check if there's a class definition problem
    if 'def create_new_file(self)' in content and 'save_btn.clicked.connect(save_file)' in content:
        # Fix indentation issues by ensuring all methods are properly defined within the class
        lines = content.split('\n')
        fixed_lines = []
        in_method = False
        current_indent = 0
        
        for line in lines:
            # Check if line starts a new method
            if line.strip().startswith('def ') and '(self' in line:
                in_method = True
                current_indent = len(line) - len(line.lstrip())
            
            # Check for class-level code that should be in a method
            if in_method and line.strip() and not line.startswith(' ' * current_indent):
                if 'save_btn.clicked.connect(save_file)' in line:
                    # This line should be indented inside a method
                    fixed_lines.append(' ' * (current_indent + 4) + line.strip())
                    continue
            
            fixed_lines.append(line)
        
        fixed_content = '\n'.join(fixed_lines)
        
        # Write fixed content
        with open(main_window_path, 'w', encoding='utf-8') as f:
            f.write(fixed_content)
        
        print("Attempted manual fix - please check if it resolved the issue.")
        return True
    
    print("Could not identify the specific issue to fix manually.")
    return False

def main():
    """Main function to fix DecentraBrowser errors."""
    # 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 files
    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
    
    # Fix main_window.py
    success = fix_main_window(main_window_py)
    
    if success:
        print("\nFix applied. Please try running DecentraBrowser again.")
        print("If issues persist, you may need to manually restore from backup or reinstall DecentraBrowser.")
    else:
        print("\nCould not fix the issue automatically.")
        print("Please restore from a backup or reinstall DecentraBrowser.")
    
    return 0

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