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)
    page.click('input[type="submit"]')
    time.sleep(2)
    
    page.fill('input[name="passwd"]', password)
    page.click('input[type="submit"]')

    # Wait for the Microsoft 2FA Number to appear on screen
    print("Waiting for 2FA prompt...")
    try:
        page.wait_for_selector('.displaySign', timeout=10000)
        auth_number = page.inner_text('.displaySign')
        
        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")
    except Exception:
        print("No number prompt detected. Might be a push notification.")

    # ---------------------------------------------------------
    # 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)
