from playwright.sync_api import sync_playwright
import time

username = "abona@iadb.org"
password = "zOVM%rwR!z69" # Replace with your actual password

def run(playwright):
    # Set headless=False so you can watch the magic happen. Change to True later.
    browser = playwright.chromium.launch(
            headless=True, 
            args=["--disable-blink-features=AutomationControlled"]
            )

    context = browser.new_context()
    page = context.new_page()

    print("Navigating to ServiceNow...")
    page.goto('https://iadb.service-now.com/sp?id=parking_pass_screen')
    time.sleep(2) # Wait for the page to load
    
    # Microsoft Login Flow
    print("Entering credentials...")
    page.fill('input[name="loginfmt"]', username)
    
    # Click and DO NOT wait for the page to load
    page.click('input[type="submit"]', no_wait_after=True)
    time.sleep(2) # Brief pause to let the password field appear
    
    page.fill('input[name="passwd"]', password)
    
    # Click and DO NOT wait for the page to load
    page.click('input[type="submit"]', no_wait_after=True)

    # Wait for the Microsoft 2FA Number to appear on screen
    print("Waiting for 2FA prompt...")
    try:
        # Wait up to 15 seconds for the authenticator screen to load
        page.wait_for_selector('.displaySign, #idRichContext_DisplaySign, #idDiv_SAOTCAS_Title', timeout=15000)
        
        # Target the specific elements that hold the number
        number_locator = page.locator('.displaySign, #idRichContext_DisplaySign').first
        
        # Check if the element exists and is visible
        if number_locator.is_visible():
            # Wait specifically for the text to not be empty
            page.wait_for_function('el => el.innerText.trim().length > 0', arg=number_locator.element_handle())
            auth_number = number_locator.inner_text().strip()
            
            print("\n" + "="*50)
            print(f"🚨 ACTION REQUIRED 🚨")
            print(f"Open Microsoft Authenticator on your phone.")
            print(f"Enter this number: {auth_number}")
            print("="*50 + "\n")
        else:
            print("\n🚨 No number match required. Please check your phone for a standard 'Approve' prompt. 🚨\n")
            
    except Exception as e:
        print("\nCould not scrape a 2FA number. Look at the browser window if headless=False!")

    # ---------------------------------------------------------
    # NEW FIX: Smart loop to handle "Stay signed in" and Redirects
    # ---------------------------------------------------------
    print("Waiting for your phone approval and handling redirects...")
    
    for _ in range(60): # 60 second timeout loop
        # 1. If we successfully reach the ServiceNow portal, break the loop
        if "iadb.service-now.com" in page.url and "login" not in page.url:
            print("Successfully redirected to ServiceNow!")
            break
            
        # 2. If the "Stay signed in?" button appears, click it immediately
        if page.locator('id=idSIButton9').is_visible():
            print("Accepting 'Stay signed in?' prompt...")
            page.click('id=idSIButton9')
            time.sleep(2) # Give it a moment to process the click
            
        time.sleep(1)
    else:
        print("Timeout: Did not reach the ServiceNow portal within 60 seconds.")
        browser.close()
        return

    # Wait for the page to fully load its elements before saving
    page.wait_for_load_state('networkidle')

    # Save the authenticated state
    context.storage_state(path="state.json")
    print("✅ Authentication successful! Session saved to state.json")

    browser.close()

if __name__ == "__main__":
    with sync_playwright() as playwright:
        run(playwright)
