# /apps/aroflo_connector_app/ui_automation/flows/users_nav.py
from __future__ import annotations

from pathlib import Path
from playwright.sync_api import Page

from ..core.artifacts import shot
from ..core.log import log_step, pause
from ..auth.post_login import handle_terminate_sessions
from ..flows import timesheet_select_bu  # reusamos tu selector de BU

USERS_URL = "https://office.aroflo.com/ims/Site/Users/index.cfm?view=1&tid=IMS.MNG.USR"


def _click_manage(page: Page) -> bool:
    candidates = [
        page.get_by_role("link", name="Manage"),
        page.get_by_role("button", name="Manage"),
        page.locator("text=Manage").first,
        page.locator("span:has-text('Manage')").first,
        page.locator("div:has-text('Manage')").first,
        page.locator("li:has-text('Manage')").first,
    ]
    for loc in candidates:
        try:
            if loc.count() == 0:
                continue
            target = loc.first if hasattr(loc, "first") else loc
            try:
                target.hover(timeout=1500)
            except Exception:
                pass
            target.click(timeout=3000, force=True)
            page.wait_for_timeout(250)
            return True
        except Exception:
            continue
    return False


def _click_users_option(page: Page) -> bool:
    # En tu HTML: data-aroflo-menuitem="manage-users" href="/ims/Site/Users/index.cfm?...tid=IMS.MNG.USR"
    candidates = [
        page.locator('a[data-aroflo-menuitem="manage-users"]').first,
        page.get_by_role("link", name="Users"),
        page.get_by_role("button", name="Users"),
        page.locator("a:has-text('Users')").first,
        page.locator("text=Users").first,
    ]

    for loc in candidates:
        try:
            if loc.count() == 0:
                continue
            loc.first.click(timeout=4000, force=True)
            return True
        except Exception:
            continue
    return False


def run(page: Page, cfg, run_dir: Path) -> None:
    # Asegura /ims/
    page.wait_for_function("() => location.href.includes('/ims/')", timeout=30_000)

    handle_terminate_sessions(page, run_dir)

    shot(page, run_dir, "users-step1-ims-ready")
    log_step("users-step1-ims-ready", page)
    pause(cfg, "Users: IMS ready")

    # Seleccionar BU ANTES de Manage (reusamos timesheet_select_bu)
    target_bu = (getattr(cfg, "timesheet_bu", "") or "").strip()
    if target_bu:
        timesheet_select_bu.run(page, cfg, run_dir, target_bu=target_bu)
        handle_terminate_sessions(page, run_dir)

        try:
            page.wait_for_load_state("domcontentloaded", timeout=15_000)
        except Exception:
            pass
        page.wait_for_timeout(300)

        shot(page, run_dir, f"users-step1b-bu-applied-{target_bu}")
        log_step(f"users-step1b-bu-applied-{target_bu}", page)
        pause(cfg, f"Users: BU applied: {target_bu}")

    # Open Manage
    _click_manage(page)
    shot(page, run_dir, "users-step2-manage-attempt")
    log_step("users-step2-manage-attempt", page)
    pause(cfg, "Users: attempted to open Manage")

    # Click Users
    clicked = _click_users_option(page)
    if not clicked:
        shot(page, run_dir, "users-step2b-users-not-found")
        log_step("users-step2b-users-not-found", page)

        page.goto(USERS_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(600)
        shot(page, run_dir, "users-step3-users-direct-goto")
        log_step("users-step3-users-direct-goto", page)
        pause(cfg, "Users: fallback direct goto Users URL")
    else:
        page.wait_for_function(
            """() => {
                const urlOk = location.href.toLowerCase().includes('/users/');
                const txt = document.body && document.body.innerText ? document.body.innerText : '';
                const txtOk = txt.includes('Users') || txt.includes('User');
                return urlOk || txtOk;
            }""",
            timeout=45_000,
        )
        shot(page, run_dir, "users-step3-users-landing")
        log_step("users-step3-users-landing", page)
        pause(cfg, "Users: landing reached")

    try:
        page.wait_for_load_state("networkidle", timeout=20_000)
    except Exception:
        pass
    
    
    shot(page, run_dir, "users-step4-users-stable")
    log_step("users-step4-users-stable", page)
