#!/root/venvs/itb/bin/python
import sys
import os
import time
import argparse
from selenium import webdriver

class NavigationController:
    def __init__(self, debug_port: int):
        """Initialize connection to Chrome instance"""
        options = webdriver.ChromeOptions()
        options.add_experimental_option("debuggerAddress", f"127.0.0.1:{debug_port}")
        self.driver = webdriver.Chrome(options=options)
        
        # Load JavaScript files
        js_dir = os.path.join(os.path.dirname(__file__), "..", "js")
        self.js_code = ""
        with open(os.path.join(js_dir, "viewport.js")) as f:
            self.js_code = f.read()
            
    def navigate(self, url: str) -> bool:
        """
        Navigate to the specified URL
        Returns True if navigation was successful
        """
        try:
            # Store initial URL for comparison
            initial_url = self.driver.current_url
            
            # Execute navigation
            self.driver.get(url)
            
            # Wait for navigation to complete
            max_wait = 10  # seconds
            start_time = time.time()
            
            while time.time() - start_time < max_wait:
                # Check if URL has changed
                if self.driver.current_url != initial_url:
                    # Wait a bit more for page to stabilize
                    time.sleep(0.5)
                    return True
                    
                time.sleep(0.1)
                
            # If we get here, navigation may have failed
            print(f"Warning: Navigation timeout after {max_wait} seconds", file=sys.stderr)
            return False
            
        except Exception as e:
            print(f"Error during navigation: {str(e)}", file=sys.stderr)
            return False

def main():
    parser = argparse.ArgumentParser(description='Navigate to URL in Chrome')
    parser.add_argument('debug_port', type=int, help='Chrome debug port')
    parser.add_argument('url', help='URL to navigate to')
    
    args = parser.parse_args()
    
    try:
        controller = NavigationController(args.debug_port)
        success = controller.navigate(args.url)
        sys.exit(0 if success else 1)
        
    except Exception as e:
        print(f"Fatal error: {str(e)}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()