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

This script does a deep scan of the main_window.py file to find and fix
all syntax errors, particularly focusing on try-except blocks.

Usage:
    python thorough_syntax_fix.py
"""

import os
import sys
import shutil
import re
import tempfile
import subprocess

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

def check_file_syntax(file_path):
    """Check if a Python file has syntax errors."""
    result = subprocess.run(
        [sys.executable, "-m", "py_compile", file_path],
        capture_output=True,
        text=True
    )
    
    if result.returncode != 0:
        print(f"Syntax error detected: {result.stderr}")
        return False, result.stderr
    
    return True, "No syntax errors detected."

def find_syntax_error_line(error_message):
    """Extract the line number from a syntax error message."""
    match = re.search(r'line (\d+)', error_message)
    if match:
        return int(match.group(1))
    return None

def fix_file_line_by_line(file_path):
    """Fix the file line by line, preserving as much as possible."""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # Track open blocks
    block_stack = []
    line_indices = {}
    
    # First pass: identify blocks and find issues
    for i, line in enumerate(lines):
        stripped = line.strip()
        
        # Skip empty lines and comments
        if not stripped or stripped.startswith('#'):
            continue
        
        # Track block starts
        if stripped.endswith(':'):
            indent_level = len(line) - len(line.lstrip())
            
            # Close blocks if we're returning to a lower indentation
            while block_stack and block_stack[-1]['indent'] >= indent_level:
                block_stack.pop()
            
            block_type = stripped.split(':')[0].split()[0]
            block_stack.append({
                'type': block_type,
                'indent': indent_level,
                'line': i
            })
            line_indices[i] = {
                'block_type': block_type,
                'indent': indent_level
            }
        
        # Check for dangling except without try
        if stripped.startswith('except') and (not block_stack or block_stack[-1]['type'] != 'try'):
            print(f"Line {i+1}: Found except without matching try: {stripped}")
            # Find closest try block
            closest_try = None
            closest_distance = float('inf')
            
            for j, block in line_indices.items():
                if block['block_type'] == 'try' and j < i:
                    distance = i - j
                    if distance < closest_distance:
                        closest_try = j
                        closest_distance = distance
            
            if closest_try is not None:
                print(f"  Closest try is at line {closest_try+1}")
                # Check if there's an except already
                has_except = False
                for j in range(closest_try+1, i):
                    if lines[j].strip().startswith('except'):
                        has_except = True
                        break
                
                if not has_except:
                    # We need to modify the code between try and this except
                    # to make it valid Python syntax
                    print(f"  Need to fix code between try at line {closest_try+1} and except at line {i+1}")
    
    # Second pass: fix issues
    fixed = False
    cleaned_lines = []
    i = 0
    
    while i < len(lines):
        line = lines[i]
        stripped = line.strip()
        
        # Handle except without try
        if stripped.startswith('except') and i > 0:
            # Look backward for a try
            j = i - 1
            while j >= 0 and not lines[j].strip().startswith('try:'):
                j -= 1
            
            if j < 0:
                # No try found, remove this except
                indent = re.match(r'^(\s*)', line).group(1)
                cleaned_lines.append(f"{indent}# Removed invalid except: {stripped}\n")
                fixed = True
                i += 1
                continue
            
            # Check if there's another except between try and this except
            has_intermediate_except = False
            for k in range(j+1, i):
                if lines[k].strip().startswith('except'):
                    has_intermediate_except = True
                    break
            
            if has_intermediate_except:
                # This is probably a duplicate except, remove it
                indent = re.match(r'^(\s*)', line).group(1)
                cleaned_lines.append(f"{indent}# Removed duplicate except: {stripped}\n")
                fixed = True
                i += 1
                continue
        
        # Check for try without except
        if stripped == 'try:':
            try_indent = re.match(r'^(\s*)', line).group(1)
            # Look ahead for an except or finally
            j = i + 1
            found_except = False
            while j < len(lines):
                next_line = lines[j].strip()
                next_indent = re.match(r'^(\s*)', lines[j]).group(1)
                
                # If we encounter a line with same or less indentation than try,
                # and it's not an except/finally, we're missing the except block
                if next_line and len(next_indent) <= len(try_indent):
                    if not (next_line.startswith('except') or next_line.startswith('finally')):
                        # Insert a generic except
                        body_indent = try_indent + "    "
                        cleaned_lines.append(line)
                        cleaned_lines.append(f"{body_indent}pass  # Added placeholder code\n")
                        cleaned_lines.append(f"{try_indent}except Exception as e:\n")
                        cleaned_lines.append(f"{body_indent}print(f\"Error: {{str(e)}}\")\n")
                        fixed = True
                        i += 1
                        break
                
                # Found an except or finally
                if next_line.startswith('except') or next_line.startswith('finally'):
                    found_except = True
                    break
                
                j += 1
            
            # If we reached the end without finding an except, add one
            if j == len(lines) and not found_except:
                body_indent = try_indent + "    "
                cleaned_lines.append(line)
                cleaned_lines.append(f"{body_indent}pass  # Added placeholder code\n")
                cleaned_lines.append(f"{try_indent}except Exception as e:\n")
                cleaned_lines.append(f"{body_indent}print(f\"Error: {{str(e)}}\")\n")
                fixed = True
                i += 1
                continue
        
        # No issues with this line, keep it
        cleaned_lines.append(line)
        i += 1
    
    # Write the fixed content
    if fixed:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.writelines(cleaned_lines)
        
        print(f"Fixed syntax issues in {file_path}")
        return True
    else:
        print("No syntax issues found that could be fixed automatically")
        return False

def rewrite_from_scratch(main_window_py):
    """Last resort approach - rewrite the file from a known good template."""
    print("\nAttempting to restore from a minimal template to ensure syntax correctness...")
    
    # Create a minimal MainWindow class that should work
    minimal_template = """#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import time
import json
import base64
import logging
import threading
import requests
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView

# Set up logging
logger = logging.getLogger(__name__)

class MainWindow(QMainWindow):
    
    
    def __init__(self, network_client, domain_server, security_manager, ddns, content_dir):
        
        super(MainWindow, self).__init__()
        self.network_client = network_client
        self.domain_server = domain_server
        self.security_manager = security_manager
        self.ddns = ddns
        self.content_dir = content_dir
        self.my_domain = None
        
        # Initialize UI
        self.init_ui()
    
    def init_ui(self):
        
        # Set window title and size
        self.setWindowTitle("DecentraBrowser")
        self.resize(1200, 800)
        
        # Create central widget and layout
        central_widget = QWidget()
        main_layout = QVBoxLayout(central_widget)
        
        # Create tab widget
        self.tabs = QTabWidget()
        
        # Create tabs
        self.tab_domains = QWidget()
        self.tab_certificates = QWidget()
        self.tab_browser = QWidget()
        self.tab_messaging = QWidget()
        
        # Add tabs to tab widget
        self.tabs.addTab(self.tab_domains, "Domains")
        self.tabs.addTab(self.tab_certificates, "Certificates")
        self.tabs.addTab(self.tab_browser, "Browser")
        self.tabs.addTab(self.tab_messaging, "Messaging")
        
        # Add tab widget to main layout
        main_layout.addWidget(self.tabs)
        
        # Set central widget
        self.setCentralWidget(central_widget)
        
        # Setup status bar
        self.statusBar().showMessage("Ready")
        
        # Setup tabs
        self.setup_domains_tab()
        self.setup_certificates_tab()
        self.setup_browser_tab()
        self.setup_messaging_tab()
        
        # Refresh domains
        try:
            self.refresh_domains()
        except Exception as e:
            print(f"Error refreshing domains: {str(e)}")
    
    def setup_domains_tab(self):
        
        layout = QVBoxLayout()
        
        # Create domains table
        self.domains_table = QTableWidget()
        self.domains_table.setColumnCount(5)
        self.domains_table.setHorizontalHeaderLabels([
            "Domain", "IP:Port", "Title", "Status", "Actions"
        ])
        
        # Add refresh button
        refresh_layout = QHBoxLayout()
        refresh_layout.addStretch()
        
        refresh_btn = QPushButton("Refresh Domains")
        refresh_btn.clicked.connect(self.refresh_domains)
        refresh_layout.addWidget(refresh_btn)
        
        # Add create domain button
        create_btn = QPushButton("Create Domain")
        create_btn.clicked.connect(self.create_domain_dialog)
        
        # Button layout
        btn_layout = QHBoxLayout()
        btn_layout.addWidget(create_btn)
        btn_layout.addStretch()
        
        # Add widgets to layout
        layout.addLayout(btn_layout)
        layout.addWidget(self.domains_table)
        layout.addLayout(refresh_layout)
        
        # Set layout for tab
        self.tab_domains.setLayout(layout)
    
    def setup_certificates_tab(self):
        
        layout = QVBoxLayout()
        
        # Label
        label = QLabel("Certificates will be shown here")
        layout.addWidget(label)
        
        # Set layout for tab
        self.tab_certificates.setLayout(layout)
    
    def setup_browser_tab(self):
        
        layout = QVBoxLayout()
        
        # Add address bar
        address_layout = QHBoxLayout()
        
        self.browser_address_bar = QLineEdit()
        self.browser_address_bar.setPlaceholderText("Enter domain or URL...")
        self.browser_address_bar.returnPressed.connect(self.navigate_to_input)
        
        self.browser_go_btn = QPushButton("Go")
        self.browser_go_btn.clicked.connect(self.navigate_to_input)
        
        address_layout.addWidget(self.browser_address_bar)
        address_layout.addWidget(self.browser_go_btn)
        
        layout.addLayout(address_layout)
        
        # Add browser view
        self.browser_view = QWebEngineView()
        layout.addWidget(self.browser_view)
        
        # Set layout for tab
        self.tab_browser.setLayout(layout)
    
    def setup_messaging_tab(self):
       
        # Create layout
        layout = QVBoxLayout()
        
        # Domain selection
        domain_layout = QHBoxLayout()
        
        domain_label = QLabel("Select Domain:")
        self.msg_domain_dropdown = QComboBox()
        
        self.msg_refresh_btn = QPushButton("Refresh")
        self.msg_refresh_btn.clicked.connect(self.refresh_message_domains)
        
        domain_layout.addWidget(domain_label)
        domain_layout.addWidget(self.msg_domain_dropdown)
        domain_layout.addWidget(self.msg_refresh_btn)
        
        # Message history
        history_group = QGroupBox("Message History")
        history_layout = QVBoxLayout()
        
        self.msg_history = QListWidget()
        
        history_buttons = QHBoxLayout()
        self.message_clear_btn = QPushButton("Clear History")
        self.message_clear_btn.clicked.connect(self.clear_message_history)
        
        history_buttons.addStretch()
        history_buttons.addWidget(self.message_clear_btn)
        
        history_layout.addWidget(self.msg_history)
        history_layout.addLayout(history_buttons)
        
        history_group.setLayout(history_layout)
        
        # Message input
        input_group = QGroupBox("Send Message")
        input_layout = QVBoxLayout()
        
        self.msg_input = QTextEdit()
        self.msg_input.setPlaceholderText("Type your message here...")
        self.msg_input.setMaximumHeight(100)
        
        send_layout = QHBoxLayout()
        send_layout.addStretch()
        
        self.msg_send_btn = QPushButton("Send")
        self.msg_send_btn.clicked.connect(self.send_message)
        
        send_layout.addWidget(self.msg_send_btn)
        
        input_layout.addWidget(self.msg_input)
        input_layout.addLayout(send_layout)
        
        input_group.setLayout(input_layout)
        
        # Add all components to the main layout
        layout.addLayout(domain_layout)
        layout.addWidget(history_group)
        layout.addWidget(input_group)
        
        # Initialize message checking timer
        self.message_timer = QTimer()
        self.message_timer.timeout.connect(self.check_for_new_messages)
        # Temporarily disabled: self.message_timer.start(10000)
        
        # Apply layout to tab
        self.tab_messaging.setLayout(layout)
    
    def refresh_domains(self):
        
        try:
            # Show refreshing status
            self.statusBar().showMessage("Refreshing domains...", 1000)
            
            # Get domains from DDNS
            success, result = self.network_client.get_domains()
            
            if success:
                # Update domains table
                self.update_domains_table(success, result)
                
                # Log success
                print(f"Domains refreshed - found {len(result)} domains")
                
                # Update status bar
                self.statusBar().showMessage(f"Found {len(result)} domains", 3000)
            else:
                # Log failure
                print(f"Failed to refresh domains: {result}")
                
                # Update status bar
                self.statusBar().showMessage(f"Failed to refresh domains: {result}", 3000)
                
                # Still try to update with empty list to clear previous data
                self.update_domains_table(False, [])
        except Exception as e:
            # Log error
            print(f"Error refreshing domains: {str(e)}")
            
            # Update status bar
            self.statusBar().showMessage(f"Error refreshing domains: {str(e)}", 5000)
    
    def update_domains_table(self, success, result):
        
        try:
            # Clear the table first
            self.domains_table.setRowCount(0)
            
            if not success:
                # Show error if we failed to get domains
                self.statusBar().showMessage(f"Failed to get domains: {result}", 5000)
                return
            
            # Process domains
            domains = result
            
            if not domains:
                # No domains to display
                self.statusBar().showMessage("No domains found", 3000)
                return
            
            # Add domains to table
            for i, domain in enumerate(domains):
                # Insert row
                self.domains_table.insertRow(i)
                
                # Get DDNS info
                in_ddns = self.ddns.has_entry(domain.full_name)
                
                # Domain name
                self.domains_table.setItem(i, 0, QTableWidgetItem(domain.full_name))
                
                # IP and Port
                ip_port = f"{domain.ip}:{domain.port}"
                self.domains_table.setItem(i, 1, QTableWidgetItem(ip_port))
                
                # Title
                title = domain.title if domain.title else ""
                self.domains_table.setItem(i, 2, QTableWidgetItem(title))
                
                # Status
                status = "ONLINE" if self.network_client.is_domain_online(domain) else "OFFLINE"
                status_item = QTableWidgetItem(status)
                status_item.setForeground(QBrush(QColor("green" if status == "ONLINE" else "red")))
                self.domains_table.setItem(i, 3, status_item)
                
                # Actions cell
                actions_widget = QWidget()
                actions_layout = QHBoxLayout(actions_widget)
                actions_layout.setContentsMargins(2, 2, 2, 2)
                
                # Different actions based on whether domain is in DDNS
                if in_ddns:
                    btn_connect = QPushButton("Connect")
                    btn_connect.setProperty("domain", domain.full_name)
                    btn_connect.clicked.connect(self.connect_to_domain)
                    
                    actions_layout.addWidget(btn_connect)
                else:
                    btn_add = QPushButton("Add to DDNS")
                    btn_add.setProperty("domain", domain.full_name)
                    btn_add.clicked.connect(self.add_to_ddns)
                    
                    actions_layout.addWidget(btn_add)
                
                self.domains_table.setCellWidget(i, 4, actions_widget)
                
            # Resize columns to content
            self.domains_table.resizeColumnsToContents()
            
            # Show success message with domain count
            self.statusBar().showMessage(f"Found {len(domains)} domains", 3000)
                
        except Exception as e:
            # Log the error
            print(f"Error updating domains table: {str(e)}")
            
            # Show error in status bar
            self.statusBar().showMessage(f"Error updating domains table: {str(e)}", 5000)
    
    def create_domain_dialog(self):
        
        dialog = QDialog(self)
        dialog.setWindowTitle("Create Domain")
        dialog.setMinimumSize(400, 300)
        
        layout = QVBoxLayout()
        
        # Domain name inputs
        name_layout = QFormLayout()
        
        prefix_input = QLineEdit()
        main_input = QLineEdit()
        suffix_input = QLineEdit()
        
        name_layout.addRow("Prefix:", prefix_input)
        name_layout.addRow("Main:", main_input)
        name_layout.addRow("Suffix:", suffix_input)
        
        # Create buttons
        button_layout = QHBoxLayout()
        create_button = QPushButton("Create Domain")
        cancel_button = QPushButton("Cancel")
        
        button_layout.addStretch()
        button_layout.addWidget(create_button)
        button_layout.addWidget(cancel_button)
        
        # Connect signals
        cancel_button.clicked.connect(dialog.reject)
        
        def create_domain():
            # Get values
            prefix = prefix_input.text()
            main = main_input.text()
            suffix = suffix_input.text()
            
            if not prefix or not main or not suffix:
                QMessageBox.warning(dialog, "Error", "All fields are required")
                return
            
            try:
                # Create domain
                from ..shared.domain import Domain
                
                # Get local IP
                def get_local_ip():
                    import socket
                    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                    try:
                        s.connect(("8.8.8.8", 80))
                        return s.getsockname()[0]
                    except:
                        return "127.0.0.1"
                    finally:
                        s.close()
                
                domain = Domain(
                    prefix=prefix,
                    main=main,
                    suffix=suffix,
                    ip=get_local_ip(),
                    port=8844
                )
                
                # Register domain
                success, result = self.network_client.register_domain(domain)
                
                if success:
                    self.my_domain = domain
                    
                    # Start domain server
                    if not self.domain_server.is_running():
                        self.domain_server.domain = domain
                        self.domain_server.start()
                    
                    QMessageBox.information(dialog, "Success", f"Domain {domain.full_name} created")
                    dialog.accept()
                    
                    # Refresh domains to show newly created domain
                    self.refresh_domains()
                else:
                    QMessageBox.warning(dialog, "Error", f"Failed to create domain: {result}")
            except Exception as e:
                QMessageBox.critical(dialog, "Error", f"Error creating domain: {str(e)}")
        
        create_button.clicked.connect(create_domain)
        
        # Add widgets to layout
        layout.addLayout(name_layout)
        layout.addLayout(button_layout)
        
        dialog.setLayout(layout)
        dialog.exec_()
    
    def connect_to_domain(self):
        
        sender = self.sender()
        domain_name = sender.property("domain")
        
        if domain_name:
            self.navigate_to_domain(domain_name)
    
    def navigate_to_domain(self, domain_name):
        
        # Update browser address bar
        if hasattr(self, 'browser_address_bar'):
            self.browser_address_bar.setText(domain_name)
        
        # Connect to domain
        success, result = self.network_client.connect_to_domain(domain_name)
        
        if success:
            # Show success message
            self.statusBar().showMessage(f"Connected to {domain_name}", 3000)
            
            # Get domain info
            html = rf"""
                    <html>
                <head>
                <title>{domain_name}</title>
                <style>
                    body {{
                        font-family: Arial, sans-serif;
                        margin: 0;
                        padding: 20px;
                        background-color: #f5f5f5;
                    }}
                    .container {{
                        max-width: 800px;
                        margin: 0 auto;
                        background-color: white;
                        padding: 20px;
                        border-radius: 5px;
                        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                    }}
                    h1 {{
                        color: #333;
                    }}
                    .domain-info {{
                        margin-bottom: 20px;
                        padding-bottom: 20px;
                        border-bottom: 1px solid #eee;
                    }}
                    .file-list {{
                        margin-top: 20px;
                    }}
                    .file-card {{
                        background-color: #f9f9f9;
                        border: 1px solid #ddd;
                        border-radius: 3px;
                        padding: 10px;
                        margin-bottom: 10px;
                    }}
                    .file-name {{
                        font-weight: bold;
                        margin-bottom: 5px;
                    }}
                    .file-size, .file-type {{
                        color: #666;
                        font-size: 0.9em;
                        margin-bottom: 5px;
                    }}
                    .download-btn {{
                        background-color: #4CAF50;
                        color: white;
                        border: none;
                        padding: 5px 10px;
                        text-align: center;
                        text-decoration: none;
                        display: inline-block;
                        font-size: 14px;
                        margin: 4px 2px;
                        cursor: pointer;
                        border-radius: 3px;
                    }}
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="domain-info">
                        <h1>{domain_name}</h1>
                        <p>Connected to {domain_name}</p>
                    </div>
                    
                    <div class="file-list">
                        <h2>Files</h2>
            """
            
            # Get files
            files = self.network_client.list_files(domain_name)
            
            if not files:
                html += "<p>No files found</p>"
            else:
                for file_name, file_info in files.items():
                    file_size = file_info.get('size', 0)
                    file_type = file_info.get('type', 'Unknown')
                    
                    html += f"""
                    <div class="file-card">
                        <div class="file-name">{file_name}</div>
                        <div class="file-size">Size: {file_size} bytes</div>
                        <div class="file-type">Type: {file_type}</div>
                        <button class="download-btn" 
                                onclick="window.location.href='/{file_name}'">Download</button>
                    </div>
                    """
            
            html += """
                    </div>
                </div>
            </body>
            </html>
            """
            
            # Load HTML in browser
            self.browser_view.setHtml(html)
            
            # Switch to browser tab
            self.tabs.setCurrentWidget(self.tab_browser)
        else:
            # Show error message
            self.statusBar().showMessage(f"Failed to connect to {domain_name}: {result}", 5000)
    
    def navigate_to_input(self):
        
        # Get the input text
        input_text = self.browser_address_bar.text().strip()
        
        if not input_text:
            return
        
        # Check if it's a domain or URL
        if "://" in input_text:
            # Handle URLs
            self.browser_view.setUrl(QUrl(input_text))
        else:
            # Handle domains
            self.navigate_to_domain(input_text)
    
    def add_to_ddns(self):
        
        sender = self.sender()
        domain_name = sender.property("domain")
        
        if domain_name:
            # Find domain in the table
            for i in range(self.domains_table.rowCount()):
                if self.domains_table.item(i, 0).text() == domain_name:
                    # Get IP and port
                    ip_port = self.domains_table.item(i, 1).text()
                    ip, port = ip_port.split(':')
                    
                    # Add to DDNS
                    self.ddns.add_entry(domain_name, ip, int(port))
                    
                    # Refresh domains
                    self.refresh_domains()
                    
                    # Show success message
                    self.statusBar().showMessage(f"Added {domain_name} to DDNS", 3000)
                    return
    
    def refresh_message_domains(self):
        
        try:
            # Clear the dropdown
            self.msg_domain_dropdown.clear()
            
            # Get domains from DDNS
            domains = self.ddns.list_entries()
            
            # Add domains to dropdown
            for domain_name in domains.keys():
                self.msg_domain_dropdown.addItem(domain_name)
            
            # Update status
            if domains:
                self.statusBar().showMessage(f"Found {len(domains)} domains for messaging", 3000)
            else:
                self.statusBar().showMessage("No domains found for messaging", 3000)
                
        except Exception as e:
            self.statusBar().showMessage(f"Error refreshing message domains: {str(e)}", 5000)
    
    def send_message(self):
        
        # Get selected domain
        domain = self.msg_domain_dropdown.currentText()
        if not domain:
            self.statusBar().showMessage("No domain selected for messaging", 3000)
            return
        
        # Get message text
        message = self.msg_input.toPlainText()
        if not message:
            self.statusBar().showMessage("No message to send", 3000)
            return
        
        # Get domain info from DDNS
        domain_info = self.ddns.get_entry(domain)
        if not domain_info:
            self.statusBar().showMessage(f"Domain information not found for {domain}", 3000)
            return
        
        # Send message
        try:
            # Connect to domain
            success, result = self.network_client.connect_to_domain(domain)
            if not success:
                self.statusBar().showMessage(f"Failed to connect to {domain}: {result}", 5000)
                return
            
            # Send message
            success, result = self.network_client.send_message(domain, message)
            
            if success:
                self.statusBar().showMessage(f"Message sent to {domain}", 3000)
                
                # Clear input
                self.msg_input.clear()
                
                # Add to message history
                self.add_message_to_history("You", domain, message)
            else:
                self.statusBar().showMessage(f"Failed to send message: {result}", 5000)
                
        except Exception as e:
            self.statusBar().showMessage(f"Error sending message: {str(e)}", 5000)
    
    def add_message_to_history(self, sender, domain, message):
        
        try:
            # Format timestamp
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
            
            # Create message item
            item = QListWidgetItem(f"[{timestamp}] {sender} @ {domain}: {message}")
            
            # Add to message history
            self.msg_history.addItem(item)
            
            # Scroll to bottom
            self.msg_history.scrollToBottom()
            
        except Exception as e:
            self.statusBar().showMessage(f"Error adding message to history: {str(e)}", 5000)
    
    def clear_message_history(self):
        
        try:
            # Confirm with user
            reply = QMessageBox.question(
                self, "Clear Message History",
                "Are you sure you want to clear all message history?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                # Clear the message history
                self.msg_history.clear()
                self.statusBar().showMessage("Message history cleared", 3000)
        except Exception as e:
            self.statusBar().showMessage(f"Error clearing message history: {str(e)}", 5000)
    
    def check_for_new_messages(self):
        
        try:
            # Get active connections
            connections = self.network_client.active_connections if hasattr(self.network_client, 'active_connections') else {}
            
            for domain, connection in connections.items():
                # Skip if no active connection
                if not connection or not hasattr(connection, 'last_message_check'):
                    continue
                
                # Check for new messages since last check
                try:
                    # Query domain for new messages
                    url = f"http://{connection.host}:{connection.port}/p2p/messages"
                    
                    # Add timestamp for getting only new messages
                    if hasattr(connection, 'last_message_time'):
                        url += f"?since={connection.last_message_time}"
                    
                    # Set last check time
                    connection.last_message_check = time.time()
                    
                    # Log the check
                    print(f"Checking for new messages from {domain}")
                except:
                    # Ignore errors for individual domains
                    pass
                    
        except Exception as e:
            # Silently handle errors to prevent timer disruption
            print(f"Error checking messages: {str(e)}")
    
    def closeEvent(self, event):
        
        # Stop the domain server if running
        if self.domain_server.is_running():
            self.domain_server.stop()
        
        event.accept()
"""
    
    # Create a temporary file with the template
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as temp:
        temp.write(minimal_template)
        temp_path = temp.name
    
    # Check if the template has syntax errors
    is_valid, message = check_file_syntax(temp_path)
    
    if not is_valid:
        print(f"Error: Even the template has syntax errors: {message}")
        os.unlink(temp_path)
        return False
    
    # Replace the original file with our template
    shutil.copy2(temp_path, main_window_py)
    os.unlink(temp_path)
    
    print(f"Restored {main_window_py} from a clean template")
    return True

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)
    
    # Check if the file has syntax errors
    is_valid, message = check_file_syntax(main_window_py)
    
    if is_valid:
        print(f"No syntax errors detected in {main_window_py}")
        return 0
    
    print(f"Syntax errors detected in {main_window_py}: {message}")
    
    # Try to fix the file line by line
    if fix_file_line_by_line(main_window_py):
        # Check if fixed
        is_valid, message = check_file_syntax(main_window_py)
        
        if is_valid:
            print(f"Successfully fixed syntax errors in {main_window_py}")
            return 0
        else:
            print(f"Could not fix all syntax errors: {message}")
    
    # If we're still here, try a full rewrite
    if rewrite_from_scratch(main_window_py):
        is_valid, message = check_file_syntax(main_window_py)
        
        if is_valid:
            print(f"Successfully restored {main_window_py} from a clean template")
            print("\nWARNING: This is a complete rewrite of the file. Some custom functionality may be lost.")
            print("If needed, you can restore from the backup at: {main_window_py}.thorough.bak")
            return 0
        else:
            print(f"Even the template has syntax errors: {message}")
    
    print("\nFailed to fix syntax errors. Manual intervention required.")
    print(f"You can restore from the backup at: {main_window_py}.thorough.bak")
    return 1

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