from __future__ import annotations

import os

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_order_for_case,
    resolve_wanyouji_account,
)
from e2e.utils.account_store import account_store
from e2e.utils.dual_browser import assert_distinct_account_contexts


@pytest.mark.s_flow_032
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_032_continue_dispatch_after_cancelled_child(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    assignment_method = os.getenv("E2E_TASK_ASSIGNMENT_METHOD", "抢单大厅").strip()
    assert assignment_method in {"抢单大厅", "指派打手", "智能派单"}, (
        "E2E_TASK_ASSIGNMENT_METHOD 仅支持：抢单大厅、指派打手、智能派单；"
        f"当前值：{assignment_method}"
    )

    store = account_store()
    order = resolve_order_for_case(
        case_id="S-FLOW-032",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_states=[
            "wanyouji_cancelled_after_revoke_rejected_wait_continue_dispatch",
            "wanyouji_previous_child_cancelled_wait_continue_dispatch",
            "wanyouji_previous_child_revoked_wait_continue_dispatch",
            "player_sub_order_revoke_approved_terminal",
            "player_recovery_completed",
            "direct_penalty_visible_to_player",
        ],
    )
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-032 使用的前一子单已取消/已撤销订单；请先执行 S-FLOW-077 或对应取消/撤销终态用例")

    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_account = resolve_wanyouji_account(order)
    player_hall_text = ""

    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-032 丸友集账号登录")

    before_text, detail_text, after_text = fulfillment_page.continue_dispatch_cancelled_child_from_workshop_order_list(
        source_order_no,
        order_title,
        assignment_method=assignment_method,
    )
    assert any(status in after_text for status in ["待接单", "已发单", "代练中", "抢单大厅"]), (
        f"S-FLOW-032 续发后未看到下一子单待接单/已发单状态；source_order_no={source_order_no}; "
        f"text={after_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-032 丸友集前一子单取消/撤销后续发下一子单：{main_order_no or source_order_no}/{assignment_method}",
    )
    if assignment_method == "抢单大厅":
        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,
            )
        player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
        assert_distinct_account_contexts(
            fulfillment_page.page,
            wanyouji_account.phone,
            player_browser_page,
            player_account.phone,
        )
        player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
        player_hall_text = player_page.verify_order_in_player_hall(source_order_no, order_title)
        bug_reporter.record_if_errors(
            account=player_account.phone,
            location=f"S-FLOW-032 打手抢单大厅可见续发订单：{main_order_no or source_order_no}",
        )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-032",
        status="task_dispatched_to_player_hall",
        current_flow_state="wanyouji_dispatched_to_player_hall",
        task_wanyouji_phone=wanyouji_account.phone,
        task_assignment_method=assignment_method,
        wanzhanggui_sub_order_list_status="previous_child_cancelled_or_revoked_with_new_dispatch",
        wanyouji_order_list_before_continue_dispatch_text=before_text[:1500],
        wanyouji_continue_dispatch_cancelled_child_detail_text=detail_text[:1500],
        wanyouji_order_list_after_continue_dispatch_text=after_text[:1500],
        player_hall_after_continue_dispatch_text=player_hall_text[:1500],
        available_for_cases=["S-FLOW-026", "S-FLOW-075"],
    )
