# apps/aroflo_connector_app/ui_automation/commands/timesheet_nav.py
from __future__ import annotations

from playwright.sync_api import sync_playwright

from ..core.browser import launch_browser_context
from ..core.artifacts import create_run_dir, shot
from ..auth.session import ensure_logged_in
from ..flows import timesheet_nav as timesheet_nav_flow


def cmd_timesheet_nav(cfg) -> int:
    """
    Usa storageState (como smoke), valida sesión, y ejecuta flow timesheet_nav.
    """
    if not cfg.state_file.exists():
        raise SystemExit(f"storageState not found: {cfg.state_file}. Run bootstrap first.")

    run_dir = create_run_dir(cfg, "timesheet-nav")

    with sync_playwright() as p:
        browser, context = launch_browser_context(p, cfg, storage_state=str(cfg.state_file))
        page = context.new_page()

        try:
            # No debe pedir MFA aquí
            ensure_logged_in(page, cfg, run_dir, mfa_code="", allow_mfa=False)

            # Ejecuta navegación + screenshots
            timesheet_nav_flow.run(page, cfg, run_dir)
            shot(page, run_dir, "ok")

            # refresca state por si cambió algo
            context.storage_state(path=str(cfg.state_file))

        except Exception as e:
            shot(page, run_dir, "99-error")
            raise

        finally:
            try:
                context.close()
            except Exception:
                pass
            try:
                browser.close()
            except Exception:
                pass

    print("[UI] timesheet-nav OK")
    print(f"[UI] Artifacts: {run_dir}")
    return 0
