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

from ..core.artifacts import shot
from ..core.log import log_step, pause


def fill_login(page: Page, cfg, run_dir) -> None:
    user = page.locator('input[name="username"], input#username, input[type="text"]')
    pw = page.locator('input[name="password"], input#password, input[type="password"]')

    page.wait_for_function(
        """() => {
            const u = document.querySelector('input[name="username"],input#username,input[type="text"]');
            const p = document.querySelector('input[name="password"],input#password,input[type="password"]');
            if (!u || !p) return false;
            const uv = u.offsetParent !== null;
            const pv = p.offsetParent !== null;
            return uv && pv;
        }""",
        timeout=30_000,
    )

    user.first.fill(cfg.username)
    pw.first.fill(cfg.password)

    shot(page, run_dir, "step2-login-filled")
    log_step("step2-login-filled", page)
    pause(cfg, "Login filled")

    lbl = page.locator('label:has-text("Remember Login")')
    if lbl.count():
        lbl.first.click(force=True)

    shot(page, run_dir, "step3-remember-login")
    log_step("step3-remember-login", page)
    pause(cfg, "Remember Login clicked")

    # Botón real: "Office Login" (no "OFFICE LOGIN")
    # Preferimos selector semántico y dejamos fallback.
    btn = page.locator(
        'button:has-text("Office Login"), button:has-text("OFFICE LOGIN"), button.af-btn--primary'
    )
    if not btn.count():
        # último fallback: submit dentro del form de login
        btn = page.locator('#loginInstance form button[type="submit"]')

    if not btn.count():
        raise RuntimeError("Office Login button not found")

    btn.first.click()

    # Esperar transición: MFA / gate post-login / o ya estar en /ims/
    page.wait_for_function(
        """() => {
            const txt = document.body && document.body.innerText ? document.body.innerText : '';
            const postLogin = document.querySelector('#postLoginType');
            const v = postLogin ? (postLogin.value || '') : '';
            const isVerifyMFA = v === 'verifyMFA' || txt.includes('Verify Your Account');
            const isTerminateSessions = v === 'terminateSessions';
            const inIMS = location.href.includes('/ims/');
            const hasPwVisible = Array.from(document.querySelectorAll('input[type="password"]'))
              .some(e => e.offsetParent !== null);
            if (isVerifyMFA) return true;
            if (isTerminateSessions) return true;
            if (inIMS && !hasPwVisible) return true;
            return false;
        }""",
        timeout=60_000,
    )

    shot(page, run_dir, "step4-after-login-click")
    log_step("step4-after-login-click", page)
