from __future__ import annotations

import os
from typing import Any

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    find_player_account,
    login_player_sub_account_by_sms,
)
from e2e.tests.订单状态流转.order_flow_member_helpers import ensure_wanyouji_player_member
from e2e.tests.订单状态流转.penalty_recovery_flow_helpers import resolve_wanyouji_account
from e2e.utils.account_store import E2EAccount, account_store
from e2e.utils.dual_browser import assert_distinct_account_contexts


@pytest.mark.s_flow_026
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_026_player_accept_dispatched_order(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    store = account_store()
    order, wanyouji_account, player_account = resolve_s_flow_026_order_and_accounts(
        page,
        settings,
        bug_reporter,
        wanzhanggui_phone,
    )

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    assignment_method = order.get("task_assignment_method", os.getenv("E2E_TASK_ASSIGNMENT_METHOD", "抢单大厅"))

    player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
    player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
    if assignment_method in {"指派打手", "智能派单"} or order.get("status") == "task_player_accepted":
        player_page.verify_order_in_player_my_orders(source_order_no, order_title)
    else:
        player_page.grab_order_from_player_hall_and_verify_my_order(source_order_no, order_title)
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"S-FLOW-026 打手立即抢单/接单：{main_order_no or source_order_no}",
    )

    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    assert_distinct_account_contexts(fulfillment_page.page, wanyouji_account.phone, player_browser_page, player_account.phone)
    wanyouji_text = fulfillment_page.search_workshop_order_list(
        fulfillment_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    assert any(key in wanyouji_text for key in ["代练中", "服务中", "已接单"]), (
        f"S-FLOW-026 打手接单后丸友集未看到代练中/服务中；source_order_no={source_order_no}; "
        f"text={wanyouji_text[:1500]}"
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-026",
        status="task_player_accepted",
        current_flow_state="player_sub_order_in_progress",
        task_player_phone=player_account.phone,
        task_wanyouji_phone=wanyouji_account.phone,
        player_accept_text="verified_my_orders",
        wanyouji_after_player_accept_text=wanyouji_text[:1500],
        wanyouji_sub_order_status="代练中",
        available_for_cases=["S-FLOW-027", "S-FLOW-037", "S-FLOW-040", "S-FLOW-078"],
    )


def resolve_s_flow_026_order_and_accounts(
    page: Page,
    settings,
    bug_reporter,
    wanzhanggui_phone: str,
) -> tuple[dict[str, Any], E2EAccount, E2EAccount]:
    store = account_store()
    payload = store.load_payload()
    explicit_main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "").strip()
    explicit_source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", os.getenv("E2E_TASK_SOURCE_ORDER_NO", "")).strip()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip()

    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if (not wanzhanggui_phone or item.get("wanzhanggui_phone") == wanzhanggui_phone)
        and (not explicit_main_order_no or item.get("main_order_no") == explicit_main_order_no)
        and (not explicit_source_order_no or item.get("source_order_no") == explicit_source_order_no)
        and item.get("current_flow_state") == "wanyouji_dispatched_to_player_hall"
        and "S-FLOW-026" in item.get("available_for_cases", [])
        and "S-FLOW-026" not in item.get("consumed_by_cases", [])
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    if not candidates:
        pytest.skip("台账中未找到可供 S-FLOW-026 使用的已发打手待接单订单；请先执行 S-FLOW-021 或 S-FLOW-032。")

    for order in candidates:
        wanyouji_account = resolve_wanyouji_account(order)
        player_account = find_player_account(wanyouji_account, explicit_player_phone)
        if player_account:
            return order, wanyouji_account, player_account
        if not explicit_player_phone:
            player_account = ensure_wanyouji_player_member(
                page=page,
                settings=settings,
                bug_reporter=bug_reporter,
                parent=wanyouji_account,
            )
            return order, wanyouji_account, player_account

    pytest.skip("S-FLOW-026 未找到目标丸友集账号下可用打手账号；可通过 E2E_TASK_PLAYER_PHONE 指定。")
