from __future__ import annotations

import os
from datetime import datetime
from pathlib import Path

import pytest
from playwright.sync_api import Page

from e2e.pages.auth_simplification_page import AuthorizationSimplificationPage
from e2e.pages.admin_page import AdminPage
from e2e.pages.product_solution_admin_page import ProductSolutionAdminPage
from e2e.pages.tenant_registration_page import AccountAlreadyRegistered, TenantRegistrationPage
from e2e.pages.tenant_subscription_page import TenantSubscriptionPage
from e2e.pages.wanzhanggui_order_page import ManualOrderData, WanyoujiFulfillmentPage, WanzhangguiOrderPage
from e2e.pages.wanzhanggui_push_page import WanzhangguiPushPage
from e2e.utils.account_store import E2EAccount, account_store
from e2e.utils.data_factory import EnterpriseRegistrationData, enterprise_data, manual_order_receive_price
from e2e.utils.image_captcha import ImageCaptchaSolver
from e2e.utils.verification_code import FeishuConfig, VerificationCodeProvider


CASE_PREFIX = "E2E-AUTH-SIMPLIFY"
FIXED_PHONE = os.getenv("E2E_AUTH_SIMPLIFICATION_FIXED_PHONE", "19159770995")
FIXED_PASSWORD = os.getenv("E2E_AUTH_SIMPLIFICATION_FIXED_PASSWORD", "test123456")
FIXED_MERCHANT_NAME = os.getenv("E2E_AUTH_SIMPLIFICATION_FIXED_MERCHANT_NAME", "个体工商户1378")
RUN_OPENING = os.getenv("E2E_AUTH_SIMPLIFICATION_ENABLE_OPENING", "0").strip().lower() in {"1", "true", "yes"}
FORCE_NEW_ENTERPRISE = os.getenv("E2E_AUTH_SIMPLIFICATION_FORCE_NEW_ENTERPRISE", "0").strip().lower() in {"1", "true", "yes"}


def pytest_configure(config):
    config.addinivalue_line("markers", "e2e_auth_simplification: Wanyouji/Wanzhanggui authorization simplification flows")


@pytest.mark.e2e_auth_simplification
@pytest.mark.e2e_seed
@pytest.mark.e2e_ledger
def test_auth_simplify_001_new_wanyouji_display_is_visible_to_wanzhanggui_and_admin(
    page: Page, settings, bug_reporter, dual_account_pages
) -> None:
    """Create one enterprise, open Wanyouji, and verify its display profile across three surfaces."""
    account = create_certified_enterprise(page, settings, bug_reporter)
    ensure_product_opened(page, settings, bug_reporter, account, "丸友集")
    account = account_store().mark_wanyouji_opened(account)
    profile = display_profile(account)

    # This page is later reused for SaaS-admin verification. Keep the headed
    # pytest window useful while the dual-account contexts perform tenant work.
    page.goto(settings.admin_url, wait_until="domcontentloaded")

    wanyouji_page, wanzhanggui_page = dual_account_pages.pair(account.phone, FIXED_PHONE)
    wanyouji = AuthorizationSimplificationPage(wanyouji_page, settings.tenant_home_url, bug_reporter)
    wanyouji.login_main_account(account.phone, account.password)
    if os.getenv("E2E_AUTH_SIMPLIFICATION_SKIP_DISPLAY_CONFIG", "0").strip().lower() not in {"1", "true", "yes"}:
        frame = wanyouji.open_wanyouji_merchant_recommendation()
        wanyouji.click_display_config(frame)
        wanyouji.save_display_config(frame, profile, qr_code=ensure_qr_placeholder())
        wanyouji.toggle_external_display(frame)

    wanzhanggui = AuthorizationSimplificationPage(wanzhanggui_page, settings.tenant_home_url, bug_reporter)
    wanzhanggui.login_main_account(FIXED_PHONE, FIXED_PASSWORD)
    verify_recommendation_detail(wanzhanggui, account.enterprise_name, "工作室名称", profile)
    if os.getenv("E2E_AUTH_SIMPLIFICATION_SKIP_ADMIN_RECOMMENDATION_CHECK", "0").strip().lower() not in {"1", "true", "yes"}:
        verify_admin_recommendation(page, settings, account.enterprise_name, profile)
    save_flow_artifact(account, profile, "wanyouji_display_ready")


@pytest.mark.e2e_auth_simplification
@pytest.mark.e2e_chain
@pytest.mark.e2e_ledger
def test_auth_simplify_002_same_enterprise_wanzhanggui_display_and_supply_initialization(
    page: Page, settings, bug_reporter, dual_account_pages
) -> None:
    """Open Wanzhanggui for the seeded enterprise and validate merchant recommendation/admin supply records."""
    account, profile = latest_flow_account("wanyouji_display_ready")
    ensure_product_opened(page, settings, bug_reporter, account, "丸掌柜")
    account = account_store().mark_wanzhanggui_opened(account)
    profile = {**profile, "intro": f"丸掌柜-{profile['intro']}"}

    wanzhanggui_page, wanyouji_page = dual_account_pages.pair(account.phone, FIXED_PHONE)
    wanzhanggui = AuthorizationSimplificationPage(wanzhanggui_page, settings.tenant_home_url, bug_reporter)
    wanzhanggui.login_main_account(account.phone, account.password)
    frame = wanzhanggui.open_wanzhanggui_workshop_authorization_new()
    wanzhanggui.click_display_config(frame)
    wanzhanggui.save_display_config(frame, profile, qr_code=ensure_qr_placeholder())
    wanzhanggui.toggle_external_display(frame)

    wanyouji = AuthorizationSimplificationPage(wanyouji_page, settings.tenant_home_url, bug_reporter)
    wanyouji.login_main_account(FIXED_PHONE, FIXED_PASSWORD)
    verify_recommendation_detail(wanyouji, account.enterprise_name, "商户名称", profile)
    verify_admin_recommendation(page, settings, account.enterprise_name, profile)
    verify_admin_merchant_supply(page, settings, account.enterprise_name)
    save_flow_artifact(account, profile, "wanzhanggui_display_ready")


@pytest.mark.e2e_auth_simplification
@pytest.mark.e2e_chain
@pytest.mark.e2e_ledger
def test_auth_simplify_003_wanyouji_apply_wanzhanggui_approve_and_dispatch(
    page: Page, settings, bug_reporter, dual_account_pages
) -> None:
    """Wanyouji applies to the fixed merchant, then approval produces an enabled strategy and a hall order."""
    account, _ = latest_flow_account("wanyouji_display_ready")
    wanyouji_page, wanzhanggui_page = dual_account_pages.pair(account.phone, FIXED_PHONE)
    wanyouji = AuthorizationSimplificationPage(wanyouji_page, settings.tenant_home_url, bug_reporter)
    wanzhanggui = AuthorizationSimplificationPage(wanzhanggui_page, settings.tenant_home_url, bug_reporter)
    wanyouji.login_main_account(account.phone, account.password)
    wanzhanggui.login_main_account(FIXED_PHONE, FIXED_PASSWORD)

    wanyouji_frame = wanyouji.open_wanyouji_merchant_recommendation()
    try:
        wanyouji.require_row(wanyouji_frame, FIXED_MERCHANT_NAME)
        target_row = wanyouji_frame.locator("tr, .ant-table-row, [class*=table-row]").filter(has_text=FIXED_MERCHANT_NAME).first
        target_row.get_by_role("button", name="申请发单", exact=True).click(timeout=5000)
        submit = wanyouji_frame.get_by_role("button", name="提交申请", exact=True).last
        submit.click(timeout=5000)
        wanyouji_page.wait_for_timeout(1200)
    except AssertionError:
        wanyouji.click_tab(wanyouji_frame, "发单商户授权")
        wanyouji.require_row(wanyouji_frame, FIXED_MERCHANT_NAME)

    wanzhanggui_frame = wanzhanggui.open_wanzhanggui_workshop_authorization_new()
    wanzhanggui.click_tab(wanzhanggui_frame, "待我审核")
    wanzhanggui.search_by_name(wanzhanggui_frame, "工作室名称", account.enterprise_name)
    review_row = wanzhanggui_frame.locator("tr, .ant-table-row, [class*=table-row]").filter(has_text=account.enterprise_name).first
    review_row.get_by_role("button", name="审核", exact=True).click(timeout=5000)
    wanzhanggui.confirm_visible_modal(wanzhanggui_frame, ["同意"])
    assert_authorized_and_dispatch(wanzhanggui_page, wanyouji_page, settings, bug_reporter, account)
    save_flow_artifact(account, {}, "authorized_and_dispatched")


@pytest.mark.e2e_auth_simplification
@pytest.mark.e2e_chain
@pytest.mark.e2e_ledger
def test_auth_simplify_004_close_reapply_approve_and_dispatch_again(
    page: Page, settings, bug_reporter, dual_account_pages
) -> None:
    """Close the established relation, exercise re-application, then dispatch again after approval."""
    account, _ = latest_flow_account("authorized_and_dispatched")
    wanyouji_page, fixed_wanzhanggui_page = dual_account_pages.pair(account.phone, FIXED_PHONE)
    wanyouji = AuthorizationSimplificationPage(wanyouji_page, settings.tenant_home_url, bug_reporter)
    wanzhanggui = AuthorizationSimplificationPage(wanyouji_page, settings.tenant_home_url, bug_reporter)
    wanyouji.login_main_account(account.phone, account.password)
    wanzhanggui.login_main_account(account.phone, account.password)

    frame = wanyouji.open_wanyouji_merchant_recommendation()
    wanyouji.click_tab(frame, "发单商户授权")
    wanyouji.search_by_name(frame, "商户名称", FIXED_MERCHANT_NAME)
    wanyouji.click_row_action(frame, FIXED_MERCHANT_NAME, ["关闭授权"])
    wanyouji.confirm_visible_modal(frame, ["确认", "确定"])

    frame = wanzhanggui.open_wanzhanggui_workshop_authorization_new()
    wanzhanggui.search_by_name(frame, "工作室名称", FIXED_MERCHANT_NAME)
    wanzhanggui.click_row_action(frame, FIXED_MERCHANT_NAME, ["申请发单", "申请推单"])
    wanzhanggui.confirm_visible_modal(frame, ["确认", "确定"])

    frame = wanyouji.open_wanyouji_merchant_recommendation()
    wanyouji.click_tab(frame, "待我审核")
    wanyouji.search_by_name(frame, "商户名称", FIXED_MERCHANT_NAME)
    wanyouji.click_row_action(frame, FIXED_MERCHANT_NAME, ["审核"])
    wanyouji.confirm_visible_modal(frame, ["同意"])
    assert_authorized_and_dispatch(fixed_wanzhanggui_page, wanyouji_page, settings, bug_reporter, account)


def create_certified_enterprise(page: Page, settings, bug_reporter) -> E2EAccount:
    resume_phone = os.getenv("E2E_AUTH_SIMPLIFICATION_RESUME_PHONE", "").strip()
    if resume_phone:
        account = account_store().find_main(resume_phone)
        assert account, f"未在账号台账找到授权简化恢复账号：{resume_phone}"
        assert account.certification_status == "approved", f"恢复账号未完成认证：{resume_phone}"
        return account
    if not RUN_OPENING:
        pytest.skip("Set E2E_AUTH_SIMPLIFICATION_ENABLE_OPENING=1 to create a new enterprise and open products.")
    resumable = None if FORCE_NEW_ENTERPRISE else next(
        (
            item
            for item in reversed(account_store().load())
            if item.account_type == "main"
            and item.enterprise_name.startswith("E2E授权简化")
            and item.certification_status == "approved"
            and item.wanyouji_status != "opened"
        ),
        None,
    )
    if resumable:
        return resumable
    provider = VerificationCodeProvider(
        mode=settings.verification_code_mode,
        static_code=settings.verification_code_static,
        feishu_config=FeishuConfig(
            app_id=settings.feishu_app_id, app_secret=settings.feishu_app_secret, chat_id=settings.feishu_chat_id,
            timeout_seconds=settings.feishu_timeout_seconds, poll_interval_seconds=settings.feishu_poll_interval_seconds,
        ),
        manual_code_file=settings.manual_code_file,
        manual_timeout_seconds=settings.manual_code_timeout_seconds,
        manual_poll_interval_seconds=settings.manual_code_poll_interval_seconds,
    )
    tenant = TenantRegistrationPage(page, settings.tenant_home_url, provider, ImageCaptchaSolver(mode=settings.image_captcha_mode), bug_reporter)
    for _ in range(settings.max_register_attempts):
        data = enterprise_data(settings.register_password, settings.phone_prefix, "E2E授权简化")
        try:
            tenant.register_enterprise(data)
            admin = AdminPage(page, settings.admin_url)
            admin.login(settings.admin_username, settings.admin_password)
            admin.approve_enterprise_certification(data.contact_name)
            account = account_store().mark_certified(data)
            return account
        except AccountAlreadyRegistered:
            tenant.logout_if_needed()
    raise AssertionError("无法创建新的授权简化测试企业")


def ensure_product_opened(page: Page, settings, bug_reporter, account: E2EAccount, product_name: str) -> None:
    if product_name == "丸友集" and account.wanyouji_status == "opened":
        return
    if product_name == "丸掌柜" and account.wanzhanggui_status == "opened":
        return
    if not RUN_OPENING:
        pytest.skip(f"{product_name}未开通；设置E2E_AUTH_SIMPLIFICATION_ENABLE_OPENING=1后运行开通链路。")
    tenant_login = TenantRegistrationPage(
        page, settings.tenant_home_url,
        VerificationCodeProvider(mode=settings.verification_code_mode), ImageCaptchaSolver(mode=settings.image_captcha_mode), bug_reporter,
    )
    subscription = TenantSubscriptionPage(page, settings.tenant_home_url, tenant_login, bug_reporter)
    if product_name == "丸友集":
        open_wanyouji_by_admin_assign(page, settings, subscription, account)
    else:
        subscription.login_certified_tenant(account.phone, account.password)
        subscription.apply_wanzhanggui(account.phone)
        assert subscription.wanzhanggui_available(), "丸掌柜未进入已开通状态；当前环境可能要求支付/专用指定开通。"


def open_wanyouji_by_admin_assign(page: Page, settings, subscription: TenantSubscriptionPage, account: E2EAccount) -> None:
    """Open the Wanyouji internal-test version through SaaS-admin's merchant subscription panel."""
    from e2e.tests.SaaS订阅邀请登录.test_prodsol_assign_001_admin_assign_open import (
        click_assign_open_entry,
        close_visible_modals,
        open_merchant_list_new,
        open_merchant_subscription_modal_strict,
        read_subscription_modal_products,
        read_subscription_row_text,
        search_and_find_merchant_row,
        submit_assign_open,
        visible_modal_text,
    )

    admin = ProductSolutionAdminPage(page, settings.admin_url)
    admin.login(settings.admin_username, settings.admin_password)
    close_visible_modals(page)
    open_merchant_list_new(page)
    merchant_row = search_and_find_merchant_row(page, account)
    open_merchant_subscription_modal_strict(page, merchant_row)
    existing_row = read_subscription_row_text(page, "丸友集")
    if "丸友集" not in read_subscription_modal_products(page) and "丸友集" not in existing_row:
        click_assign_open_entry(page)
        selected_product, selected_version = select_wanyouji_internal_assign_version(page)
        assert selected_product == "丸友集", f"指定开通选择的产品错误：{selected_product}"
        assert selected_version == "内测版", f"指定开通选择的版本错误：{selected_version}"
        if os.getenv("E2E_AUTH_SIMPLIFICATION_PAUSE_BEFORE_ASSIGN_SUBMIT", "0").strip().lower() in {"1", "true", "yes"}:
            page.pause()
        submit_assign_open(page)

        close_visible_modals(page)
        open_merchant_list_new(page)
        merchant_row = search_and_find_merchant_row(page, account)
        open_merchant_subscription_modal_strict(page, merchant_row)

    row_text = read_subscription_row_text(page, "丸友集")
    if "内测版" not in row_text:
        switch_wanyouji_subscription_to_internal_test(page, account.enterprise_name)
        close_visible_modals(page)
        open_merchant_list_new(page)
        merchant_row = search_and_find_merchant_row(page, account)
        open_merchant_subscription_modal_strict(page, merchant_row)
        row_text = read_subscription_row_text(page, "丸友集")
    assert "丸友集" in row_text and "内测版" in row_text, (
        f"后台指定开通后订阅未展示丸友集内测版：merchant={account.enterprise_name}; row={row_text}; "
        f"modal={visible_modal_text(page)[:1200]}"
    )
    close_visible_modals(page)

    if os.getenv("E2E_AUTH_SIMPLIFICATION_SKIP_TENANT_AVAILABILITY_CHECK", "0").strip().lower() in {"1", "true", "yes"}:
        return

    availability_attempts = int(os.getenv("E2E_AUTH_SIMPLIFICATION_AVAILABILITY_ATTEMPTS", "40"))
    for _ in range(availability_attempts):
        subscription.login_certified_tenant(account.phone, account.password)
        try:
            if subscription.wanyouji_available():
                return
        except AssertionError:
            pass
        page.wait_for_timeout(3000)
    raise AssertionError(
        f"后台指定开通丸友集内测版后{availability_attempts * 3}秒内未显示已开通"
    )


def switch_wanyouji_subscription_to_internal_test(page: Page, enterprise_name: str) -> None:
    """Correct a default-offered Wanyouji subscription through the admin version-change action."""
    from e2e.tests.SaaS订阅邀请登录.test_prodsol_wyjadjust_001_wanyouji_adjust_default import (
        click_subscription_product_action,
        fill_adjust_reason,
    )
    from e2e.tests.SaaS订阅邀请登录.test_prodsol_wyjmenu_001_wanyouji_menu_button_config import (
        select_internal_test_version,
        submit_internal_test_version_adjustment,
    )

    click_subscription_product_action(page, "丸友集", ["调整版本"])
    select_internal_test_version(page)
    fill_adjust_reason(page, f"{CASE_PREFIX} {enterprise_name} 切换内测版")
    submit_internal_test_version_adjustment(page)


def select_wanyouji_internal_assign_version(page: Page) -> tuple[str, str]:
    """Select exactly 丸友集 / 内测版 in the active 指定开通 modal."""
    selected_product = str(page.evaluate("""({ expected, side }) => {
      const root = Array.from(document.querySelectorAll('.ant-modal, .ant-drawer'))
        .reverse().find(el => el.offsetParent !== null) || document.body;
      const compact = value => (value || '').replace(/\\s+/g, '').trim();
      const rootRect = root.getBoundingClientRect();
      const candidates = Array.from(root.querySelectorAll('*'))
        .filter(el => el.offsetParent !== null)
        .filter(el => compact(el.innerText || el.textContent) === expected)
        .filter(el => {
          const rect = el.getBoundingClientRect();
          return side === 'left' ? rect.x < rootRect.x + rootRect.width * 0.55 : rect.x >= rootRect.x + rootRect.width * 0.38;
        })
        .sort((a, b) => {
          const ar = a.getBoundingClientRect(); const br = b.getBoundingClientRect();
          return (ar.width * ar.height) - (br.width * br.height);
        });
      const target = candidates[0];
      if (!target) return '';
      const clickable = target.closest('label, .ant-radio-wrapper, .ant-checkbox-wrapper, li, .ant-list-item, .ant-card, .ant-table-row, tr, button, a, [role="button"]') || target;
      clickable.scrollIntoView({ block: 'center', inline: 'center' });
      clickable.click();
      return expected;
    }""", {"expected": "丸友集", "side": "left"}))
    assert selected_product == "丸友集", "指定开通弹框未找到丸友集产品候选"
    page.wait_for_timeout(900)
    selected_version = str(page.evaluate("""({ expected }) => {
      const root = Array.from(document.querySelectorAll('.ant-modal, .ant-drawer'))
        .reverse().find(el => el.offsetParent !== null) || document.body;
      const compact = value => (value || '').replace(/\\s+/g, '').trim();
      const rootRect = root.getBoundingClientRect();
      const candidates = Array.from(root.querySelectorAll('*'))
        .filter(el => el.offsetParent !== null)
        .filter(el => compact(el.innerText || el.textContent) === expected)
        .filter(el => el.getBoundingClientRect().x >= rootRect.x + rootRect.width * 0.38)
        .sort((a, b) => {
          const ar = a.getBoundingClientRect(); const br = b.getBoundingClientRect();
          return (ar.width * ar.height) - (br.width * br.height);
        });
      const target = candidates[0];
      if (!target) return '';
      const clickable = target.closest('label, .ant-radio-wrapper, .ant-checkbox-wrapper, li, .ant-list-item, .ant-card, .ant-table-row, tr, button, a, [role="button"]') || target;
      clickable.scrollIntoView({ block: 'center', inline: 'center' });
      clickable.click();
      return expected;
    }""", {"expected": "内测版"}))
    return selected_product, selected_version


def assert_authorized_and_dispatch(
    wanzhanggui_page: Page, wanyouji_page: Page, settings, bug_reporter, workshop: E2EAccount
) -> None:
    push = WanzhangguiPushPage(wanzhanggui_page, settings.tenant_home_url, bug_reporter)
    push.login_main_account(FIXED_PHONE, FIXED_PASSWORD)
    authorization_frame = push.open_workshop_authorization()
    assert push.workshop_authorized(authorization_frame, workshop.enterprise_name), "工作室授权未启用"
    strategy_frame = push.open_dispatch_strategy()
    assert workshop.enterprise_name in strategy_frame.locator("body").inner_text(timeout=5000), "未找到自动生成的工作室策略"

    stamp = datetime.now().strftime("%m%d%H%M%S")
    order = ManualOrderData(
        source_order_no=f"AUTH{stamp}", order_title=f"授权简化{stamp}", strategy_name=workshop.enterprise_name,
        strategy_type="单平台指定", receive_price=manual_order_receive_price(), dispatch_price="1", role_name=f"E2E角色{stamp[-4:]}",
    )
    order_page = WanzhangguiOrderPage(wanzhanggui_page, settings.tenant_home_url, bug_reporter)
    order_page.login_main_account(FIXED_PHONE, FIXED_PASSWORD)
    order_page.create_manual_order(order)
    fulfillment = WanyoujiFulfillmentPage(wanyouji_page, settings.tenant_home_url, bug_reporter)
    fulfillment.login_main_account(workshop.phone, workshop.password)
    fulfillment.verify_order_reached_hall(order.source_order_no, order.order_title, "私单")
    account_store().mark_workshop_authorized(workshop, FIXED_PHONE)
    account_store().mark_dispatch_strategy_created(workshop, FIXED_PHONE, workshop.enterprise_name, "单平台指定")
    account_store().mark_order_dispatched(
        wanzhanggui_phone=FIXED_PHONE, source_order_no=order.source_order_no, order_title=order.order_title,
        strategy_name=order.strategy_name, strategy_type=order.strategy_type, wanyouji_phones=[workshop.phone],
    )


def verify_recommendation_detail(app: AuthorizationSimplificationPage, name: str, label: str, profile: dict[str, str]) -> None:
    last_error: AssertionError | None = None
    for attempt in range(2):
        frame = app.open_wanzhanggui_workshop_authorization_new() if label == "工作室名称" else app.open_wanyouji_merchant_recommendation()
        app.search_by_name(frame, label, name)
        try:
            text = app.require_row(frame, name)
            for value in profile.values():
                assert value in text, f"推荐记录未展示配置值 {value}；text={text[:1800]}"
            return
        except AssertionError as exc:
            last_error = exc
            if attempt == 0:
                app.page.reload(wait_until="domcontentloaded")
                app.page.wait_for_timeout(1200)
    raise last_error or AssertionError(f"推荐页未找到工作室：{name}")


def verify_admin_recommendation(page: Page, settings, name: str, profile: dict[str, str]) -> None:
    admin_search(page, settings, "推荐评分配置", name)
    text = page.locator("body").inner_text(timeout=5000)
    assert name in text, f"Admin推荐评分配置未找到对象 {name}"
    for value in [profile["intro"], profile["contact"], profile["phone"], profile["wechat"], profile["qq"]]:
        assert value in text, f"Admin推荐评分配置未展示 {value}"


def verify_admin_merchant_supply(page: Page, settings, name: str) -> None:
    admin_search(page, settings, "商户供应链管理", name)
    assert name in page.locator("body").inner_text(timeout=5000), f"商户供应链管理未搜索到 {name}"


def admin_search(page: Page, settings, menu: str, keyword: str) -> None:
    from e2e.pages.admin_page import AdminPage

    admin = AdminPage(page, settings.admin_url)
    admin.login(settings.admin_username, settings.admin_password)
    admin.click_exact_text("供应链管理", timeout=5000)
    admin.click_exact_text(menu, timeout=5000)
    page.wait_for_timeout(1200)
    field = page.locator("#objectName") if menu == "推荐评分配置" else page.locator("input[placeholder*='名称'], input[placeholder*='商户']").first
    if not field.is_visible(timeout=1500):
        field = page.locator("input:not([type='hidden']):not([disabled]):not([readonly])").first
    field.fill(keyword)
    if menu == "推荐评分配置":
        clicked = page.evaluate(
            """() => {
                const wanted = '\\u67e5\\u8be2';
                const visible = el => {
                    const rect = el.getBoundingClientRect();
                    return rect.width > 0 && rect.height > 0;
                };
                const nodes = Array.from(document.querySelectorAll('button, a, [role="button"], span, div'))
                  .filter(visible)
                  .filter(el => (el.innerText || el.textContent || '').replace(/\\s+/g, '') === wanted)
                  .sort((left, right) => {
                      const a = left.getBoundingClientRect();
                      const b = right.getBoundingClientRect();
                      return a.width * a.height - b.width * b.height;
                  });
                const target = nodes[0];
                if (!target) return false;
                (target.closest('button, a, [role="button"]') || target).click();
                return true;
            }"""
        )
        assert clicked, "推荐评分配置未找到查询按钮"
    else:
        try:
            admin.click_exact_text("搜索", timeout=1500)
        except AssertionError:
            field.press("Enter")
    page.wait_for_timeout(1200)


def display_profile(account: E2EAccount) -> dict[str, str]:
    suffix = account.phone[-4:]
    return {
        "intro": f"E2E授权展示{suffix}", "game": "三角洲行动", "settlement": "周结",
        "contact": f"联系人{suffix}", "phone": f"1390000{suffix}", "wechat": f"e2e-wx-{suffix}", "qq": f"9{suffix}",
    }


def ensure_qr_placeholder() -> Path:
    path = Path("runtime/auth_simplification_qr.png")
    path.parent.mkdir(parents=True, exist_ok=True)
    if not path.exists():
        path.write_bytes(bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010802000000907753de0000000c4944415408d763f8ffff3f0005fe02fea73581e80000000049454e44ae426082"))
    return path.resolve()


def save_flow_artifact(account: E2EAccount, profile: dict[str, str], stage: str) -> None:
    path = Path("runtime/auth_simplification_flow.json")
    path.write_text(
        __import__("json").dumps({"phone": account.phone, "enterprise_name": account.enterprise_name, "profile": profile, "stage": stage}, ensure_ascii=False),
        encoding="utf-8",
    )


def latest_flow_account(required_stage: str) -> tuple[E2EAccount, dict[str, str]]:
    import json

    path = Path("runtime/auth_simplification_flow.json")
    if not path.exists():
        pytest.skip("未找到授权简化前序流程产物，请先执行AUTO-FLOW-AUTH-001/002/003。")
    payload = json.loads(path.read_text(encoding="utf-8"))
    if payload.get("stage") != required_stage:
        pytest.skip(f"前序流程未达到 {required_stage}，当前={payload.get('stage')}")
    account = account_store().find_main(str(payload["phone"]))
    assert account, f"台账未找到前序企业账号 {payload['phone']}"
    return account, dict(payload.get("profile") or {})
