from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineUrlRequestInterceptor



class ChromeWebEnginePage(QWebEnginePage):
    """
    Custom QWebEnginePage that allows navigation to chrome:// URLs
    """
    def certificateError(self, error):
        # Accept all certificates to allow chrome:// URLs
        return True
        
    def javaScriptConsoleMessage(self, level, message, line, source):
        # Log JavaScript console messages
        print(f"JS Console ({source}:{line}): {message}")
    
    def acceptNavigationRequest(self, url, type, isMainFrame):
        # Always accept chrome:// URLs
        if url.scheme() == "chrome":
            print(f"Accepting chrome:// URL navigation: {url.toString()}")
            return True
        return super().acceptNavigationRequest(url, type, isMainFrame)
    
    def createWindow(self, windowType):
        """Create a new window when requested, especially for chrome:// URLs"""
        # Get the main browser window
        browser = self.parent().window()
        from shmcs.qtbrowser.browser import Browser
        if isinstance(browser, Browser):
            # Create a new tab with our custom page
            tab = browser.new_page("about:blank")
            if hasattr(tab, 'web_view'):
                # Ensure it's using our custom page class
                if not isinstance(tab.web_view.page(), ChromeWebEnginePage):
                    page = ChromeWebEnginePage(browser.profile, tab.web_view)
                    tab.web_view.setPage(page)
                return tab.web_view.page()
        
        # Fallback: create a default page
        return ChromeWebEnginePage(self.profile())
    
    def javaScriptAlert(self, securityOrigin, msg):
        """Handle JavaScript alerts, especially from chrome:// URLs"""
        print(f"JS Alert from {securityOrigin.toString()}: {msg}")
        # Allow alerts from chrome:// URLs to pass through
        return super().javaScriptAlert(securityOrigin, msg)
    
    def javaScriptConfirm(self, securityOrigin, msg):
        """Handle JavaScript confirms, especially from chrome:// URLs"""
        print(f"JS Confirm from {securityOrigin.toString()}: {msg}")
        # Allow confirms from chrome:// URLs to pass through
        return super().javaScriptConfirm(securityOrigin, msg)
    
    def urlChanged(self, url):
        """Handle URL changes, especially to chrome:// URLs"""
        if url.scheme() == "chrome":
            print(f"URL changed to chrome:// URL: {url.toString()}")
        super().urlChanged(url)



class ChromeUrlInterceptor(QWebEngineUrlRequestInterceptor):
    """
    Intercepts URL requests to handle chrome:// URLs specially
    """
    def __init__(self, browser):
        super().__init__()
        self.browser = browser
    
    def interceptRequest(self, info):
        url = info.requestUrl()
        if url.scheme() == "chrome":
            print(f"Intercepted chrome:// URL: {url.toString()}")
            # We don't block the request, just log it for debugging
            # The actual handling is done by ChromeWebEnginePage
        if url.scheme() == 'qextension':
           print("*****************************************************")
           print(info)

