# apps/aroflo_connector_app/ui_automation/flows/timesheet_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
from ..flows import timesheet_select_user

TIMESHEETS_URL = "https://office.aroflo.com/ims/Site/Resource/Timesheet/Index.cfm?view=1&tid=IMS.MNG.TST"


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_timesheets_option(page: Page) -> bool:
    candidates = [
        page.get_by_role("link", name="Timesheets"),
        page.get_by_role("link", name="Timesheet"),
        page.get_by_role("button", name="Timesheets"),
        page.get_by_role("button", name="Timesheet"),
        page.locator("a:has-text('Timesheets')").first,
        page.locator("a:has-text('Timesheet')").first,
        page.locator("text=Timesheets").first,
        page.locator("text=Timesheet").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:
    # 0) Confirmar que estamos en /ims/
    page.wait_for_function("() => location.href.includes('/ims/')", timeout=30_000)

    handle_terminate_sessions(page, run_dir)

    shot(page, run_dir, "step1-ims-ready")
    log_step("step1-ims-ready", page)
    pause(cfg, "Step 1: IMS ready (pre-navigation)")

    # DEBUG (quítalo luego)
    try:
        v = getattr(cfg, "timesheet_bu", None)
        log_step(f"debug-timesheet_bu={v!r}", page)
    except Exception:
        pass

    # 0c) Seleccionar BU ANTES de Manage
    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)

        # Screenshot EXACTO que estás pidiendo: Home con BU ya cambiado
        shot(page, run_dir, f"step1b-bu-applied-{target_bu}")
        log_step(f"step1b-bu-applied-{target_bu}", page)
        pause(cfg, f"Step 1B: BU applied: {target_bu}")

    # 1) Intentar abrir Manage
    _click_manage(page)

    shot(page, run_dir, "step2-manage-attempt")
    log_step("step2-manage-attempt", page)
    pause(cfg, "Step 2: attempted to open Manage")

    # 2) Intentar click en Timesheets
    clicked = _click_timesheets_option(page)
    if not clicked:
        shot(page, run_dir, "step2b-timesheets-not-found")
        log_step("step2b-timesheets-not-found", page)

        page.goto(TIMESHEETS_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(600)

        shot(page, run_dir, "step3-timesheets-direct-goto")
        log_step("step3-timesheets-direct-goto", page)
        pause(cfg, "Fallback: went directly to Timesheets URL")
    else:
        page.wait_for_function(
            """() => {
                const urlOk = location.href.toLowerCase().includes('timesheet');
                const txt = document.body && document.body.innerText ? document.body.innerText : '';
                const txtOk = txt.includes('Timesheet') || txt.includes('Timesheets');
                return urlOk || txtOk;
            }""",
            timeout=45_000,
        )
        shot(page, run_dir, "step3-timesheets-landing")
        log_step("step3-timesheets-landing", page)
        pause(cfg, "Step 3: Timesheets landing reached")

    try:
        page.wait_for_load_state("networkidle", timeout=20_000)
    except Exception:
        pass
    
    uid = (getattr(cfg, "timesheet_user_id", "") or "").strip()
    uname = (getattr(cfg, "timesheet_user_name", "") or "").strip()

    if uid or uname:
        timesheet_select_user.run(
            page,
            cfg,
            run_dir,
            user_id=uid,
            user_name=uname,
        )


    shot(page, run_dir, "step4-timesheets-stable")
    log_step("step4-timesheets-stable", page)
