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

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


def handle_terminate_sessions(page: Page, run_dir) -> bool:
    """
    Maneja el modal 'User Session Limit'.
    Retorna True si fue detectado y manejado.
    """

    post_login = page.locator("#postLoginType")
    if post_login.count() == 0:
        return False

    try:
        value = post_login.first.input_value(timeout=500)
    except Exception:
        value = page.evaluate(
            "document.querySelector('#postLoginType')?.value || ''"
        )

    if value != "terminateSessions":
        return False

    shot(page, run_dir, "terminateSessions-detected")
    log_step("terminateSessions-detected", page)

    # Botón CONTINUE (verde)
    btn = page.locator("form#frmPostLogin button.af-btn--seaGreen").first
    btn.click(timeout=5000)

    page.wait_for_function(
        """() => {
            const el = document.querySelector('#postLoginType');
            return !el || el.value !== 'terminateSessions';
        }""",
        timeout=15000,
    )

    shot(page, run_dir, "terminateSessions-after")
    log_step("terminateSessions-after", page)

    try:
        page.wait_for_load_state("networkidle", timeout=15000)
    except Exception:
        pass

    return True


# Alias para compatibilidad con imports viejos
def handle_terminate_sessions_if_present(page: Page, run_dir) -> bool:
    return handle_terminate_sessions(page, run_dir)