#/apps/aroflo_connector_app/ui_automation/auth/detect.py
from playwright.sync_api import Page


def has_visible_password_input(page: Page) -> bool:
    pw = page.locator('input[type="password"]')
    for i in range(min(pw.count(), 10)):
        try:
            if pw.nth(i).is_visible():
                return True
        except Exception:
            pass
    return False


def is_mfa_screen(page: Page) -> bool:
    try:
        if page.locator("text=Verify Your Account").count() > 0:
            return True
        loc = page.locator("#postLoginType")
        if loc.count() > 0:
            return (loc.first.get_attribute("value") or "").strip() == "verifyMFA"
    except Exception:
        pass
    return False


def is_office_field_selector(page: Page) -> bool:
    try:
        return (
            page.locator("text=Office").count() > 0
            and page.locator("text=Field").count() > 0
            and page.locator('input[type="password"]').count() == 0
        )
    except Exception:
        return False


def click_office_tile(page: Page) -> None:
    for sel in (
        'a:has-text("Office")',
        'button:has-text("Office")',
        'div:has-text("Office")',
        'text=Office',
    ):
        loc = page.locator(sel)
        if loc.count() > 0:
            loc.first.click()
            return
    raise RuntimeError("Office tile not found")


def is_authenticated(page: Page) -> bool:
    try:
        if "/ims/" not in page.url:
            return False
        if has_visible_password_input(page):
            return False
        if is_mfa_screen(page):
            return False
        return True
    except Exception:
        return False
