#!/usr/bin/env python3
"""
DecentraBrowser Restore Script

This script restores the main_window.py file from the oldest backup,
which should be in a working state before any of our modifications.

Usage:
    python restore_script.py
"""

import os
import sys
import shutil
import glob
import re

def find_backups(file_path):
    """Find all backup files for a given file."""
    directory = os.path.dirname(file_path)
    base_name = os.path.basename(file_path)
    
    # Look for files like main_window.py.*.bak
    backup_pattern = os.path.join(directory, f"{base_name}.*.bak")
    backups = glob.glob(backup_pattern)
    
    # Sort by creation time (oldest first)
    backups.sort(key=lambda x: os.path.getctime(x))
    
    return backups

def find_working_backup(backups):
    """Try to find a working backup by checking syntax."""
    for backup in backups:
        try:
            with open(backup, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Try to compile the file to check syntax
            compile(content, backup, 'exec')
            
            # If we get here, the file has valid syntax
            print(f"Found valid backup: {backup}")
            return backup
        except SyntaxError:
            print(f"Backup {backup} has syntax errors, trying next...")
    
    print("No valid backups found.")
    return None

def restore_from_backup(file_path, backup_path):
    """Restore file from backup."""
    try:
        # Create one more backup of the current file
        final_backup = f"{file_path}.final_broken.bak"
        shutil.copy2(file_path, final_backup)
        print(f"Created final backup of broken file: {final_backup}")
        
        # Restore from working backup
        shutil.copy2(backup_path, file_path)
        print(f"Restored {file_path} from {backup_path}")
        return True
    except Exception as e:
        print(f"Error restoring from backup: {str(e)}")
        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
    
    # Find all backups
    backups = find_backups(main_window_py)
    
    if not backups:
        print("No backups found. Cannot restore.")
        return 1
    
    print(f"Found {len(backups)} backups:")
    for i, backup in enumerate(backups):
        print(f"{i+1}. {backup}")
    
    # Try to find a working backup
    working_backup = find_working_backup(backups)
    
    if not working_backup:
        # Prompt the user to select a backup
        print("\nNo automatically verified working backup. Please select a backup to restore from:")
        for i, backup in enumerate(backups):
            print(f"{i+1}. {backup}")
        
        selection = input("\nEnter the number of the backup to restore (or 'q' to quit): ")
        
        if selection.lower() == 'q':
            print("Restoration cancelled.")
            return 0
        
        try:
            index = int(selection) - 1
            if index < 0 or index >= len(backups):
                print("Invalid selection.")
                return 1
            
            working_backup = backups[index]
        except ValueError:
            print("Invalid input.")
            return 1
    
    # Restore from the selected backup
    if restore_from_backup(main_window_py, working_backup):
        print("\nFile restored successfully!")
        print("Please restart DecentraBrowser to apply the changes.")
        return 0
    else:
        print("\nFailed to restore file.")
        return 1

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