# setup_auth.py
from playwright.sync_api import sync_playwright  # type: ignore[reportMissingImports]
import time

username = "abona@iadb.org"
password = "zOVM%rwR!z69" # Use environment variables in production!

def run(playwright):
    browser = playwright.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()

    print("Navigating to ServiceNow...")
    page.goto('https://iadb.service-now.com/sp?id=parking_pass_screen')

    # Microsoft Login Flow
    print("Entering credentials...")
    page.fill('input[name="loginfmt"]', username)
    page.click('input[type="submit"]')
    time.sleep(2) # Brief pause for animation
    
    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:
        # Microsoft's standard element for the number matching display
        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 as e:
        print("No number matching prompt detected. Might be a push notification or already authenticated.")

    # Wait for the login to complete and redirect back to ServiceNow
    print("Waiting for your phone approval...")
    page.wait_for_url('**iadb.service-now.com/sp**', timeout=60000)
    
    # Handle the "Stay signed in?" prompt if it appears
    if page.locator('id=idSIButton9').is_visible():
        page.click('id=idSIButton9')

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