from __future__ import annotations

import os

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage, WanzhangguiOrderPage
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.订单状态流转.上游发单.test_s_flow_021_dispatch_accepted_order_to_player import (
    resolve_s_flow_021_order,
    resolve_wanyouji_phone,
)
from e2e.utils.account_store import account_store
from e2e.utils.dual_browser import assert_distinct_account_contexts


@pytest.mark.s_flow_079
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_079_dispatch_accepted_order_to_assigned_player(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    wanzhanggui_password = os.getenv("E2E_ORDER_WANZHANGGUI_PASSWORD", settings.wanzhanggui_tenant_password)
    store = account_store()
    order = resolve_s_flow_079_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-079 使用的丸友集已接单未发打手订单；请先执行 S-FLOW-014。")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    wanyouji_phone = resolve_wanyouji_phone(order)
    wanyouji_account = store.find(phone=wanyouji_phone)
    assert wanyouji_account is not None, f"台账中未找到 S-FLOW-079 丸友集账号：{wanyouji_phone}"

    player_account = find_player_account(wanyouji_account, os.getenv("E2E_TASK_PLAYER_PHONE", "").strip())
    if player_account is None:
        player_account = ensure_wanyouji_player_member(
            page=page,
            settings=settings,
            bug_reporter=bug_reporter,
            parent=wanyouji_account,
        )

    assert order.get("current_flow_state") in {
        "wanyouji_accepted_without_player_dispatch",
        "wanyouji_accepted_without_player_dispatch_after_player_withdraw",
    }, f"S-FLOW-079 前置台账状态不满足丸友集已接单未发打手；order={order}"

    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    bug_reporter.record_if_errors(account=wanyouji_account.phone, location="S-FLOW-079 丸友集账号登录")

    before_list_text = fulfillment_page.search_workshop_order_list(
        fulfillment_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    row_text = fulfillment_page.extract_order_row_text(before_list_text, source_order_no)
    row_status = fulfillment_page.extract_workshop_order_row_status(row_text)
    assert "已接单" in row_status or "代练中" in row_status or "立即发单" in row_text, (
        f"S-FLOW-079 前置状态不满足丸友集已接单未发打手；source_order_no={source_order_no}; "
        f"row_text={row_text[:1500]}"
    )

    assigned_player_order_no = fulfillment_page.dispatch_workshop_order_to_player_hall(
        source_order_no,
        order_title,
        assignment_method="指派打手",
        player_name=player_account.contact_name,
        player_phone=player_account.phone,
    )
    after_list_text = fulfillment_page.search_workshop_order_list(
        fulfillment_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    assert source_order_no in after_list_text or order_title in after_list_text, (
        f"S-FLOW-079 指派打手发单后丸友集订单列表未找到订单；source_order_no={source_order_no}; "
        f"text={after_list_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-079 丸友集指派打手发单：{main_order_no or source_order_no}/{player_account.phone}",
    )

    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)
    assigned_player_text = ""
    frames = player_page.open_player_assigned_order_hall()
    for assigned_frame in frames:
        assigned_player_text = player_page.search_player_assigned_orders(assigned_frame, assigned_player_order_no)
        if assigned_player_order_no in assigned_player_text:
            break
    assert assigned_player_order_no in assigned_player_text, (
        f"S-FLOW-079 指派发单后打手抢单大厅-指派单未找到订单；"
        f"assigned_player_order_no={assigned_player_order_no}; text={assigned_player_text[:1500]}"
    )
    assert_distinct_account_contexts(
        fulfillment_page.page,
        wanyouji_account.phone,
        player_browser_page,
        player_account.phone,
    )
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"S-FLOW-079 被指派打手抢单大厅-指派单可见待接单：{main_order_no or source_order_no}",
    )

    order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, bug_reporter)
    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    assert_distinct_account_contexts(
        fulfillment_page.page,
        wanyouji_account.phone,
        order_page.page,
        wanzhanggui_phone,
    )
    detail_status_text = order_page.assert_order_detail_statuses(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        expected_main_status=["代练中", "服务中"],
        expected_sub_status_parts=["代练中"],
        expected_sub_order_list_status=["服务中", "代练中", "已接单", "已发布"],
        expected_aftersale_absent=True,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-079 丸掌柜订单详情指派打手发单后状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-079",
        status="task_dispatched_to_assigned_player",
        current_flow_state="assigned_player_pending_accept",
        task_wanyouji_phone=wanyouji_account.phone,
        task_assignment_method="指派打手",
        task_player_phone=player_account.phone,
        task_player_name=player_account.contact_name,
        assigned_player_sub_order_no=assigned_player_order_no,
        wanzhanggui_main_status="代练中",
        wanzhanggui_sub_order_status="代练中",
        wanyouji_order_list_before_assigned_dispatch_text=before_list_text[:1500],
        wanyouji_order_list_after_assigned_dispatch_text=after_list_text[:1500],
        player_after_assigned_dispatch_assigned_hall_text=assigned_player_text[:1500],
        wanzhanggui_after_assigned_player_dispatch_detail_status_text=detail_status_text[:1500],
        available_for_cases=["S-FLOW-037", "S-FLOW-075"],
    )


def resolve_s_flow_079_order(wanzhanggui_phone: str) -> dict | None:
    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", "").strip()
    if explicit_main_order_no or explicit_source_order_no:
        payload = account_store().load_payload()
        for item in payload.get("dispatched_orders", []):
            if wanzhanggui_phone and item.get("wanzhanggui_phone") != wanzhanggui_phone:
                continue
            if explicit_main_order_no and item.get("main_order_no") != explicit_main_order_no:
                continue
            if explicit_source_order_no and item.get("source_order_no") != explicit_source_order_no:
                continue
            return item
        return None
    return resolve_s_flow_021_order(wanzhanggui_phone)
