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 login_player_sub_account_by_sms
from e2e.tests.订单状态流转.penalty_recovery_flow_helpers import (
    resolve_order_for_case,
    resolve_player_account,
    resolve_wanyouji_account,
)
from e2e.utils.account_store import account_store
from e2e.utils.dual_browser import assert_distinct_account_contexts


def _assert_wanyouji_cancel_apply_visible(wanyouji_text: str, source_order_no: str, order_title: str) -> None:
    marker = source_order_no if source_order_no in wanyouji_text else order_title
    marker_index = wanyouji_text.find(marker)
    order_context = wanyouji_text if marker_index < 0 else wanyouji_text[max(0, marker_index - 300) : marker_index + 900]
    assert marker in wanyouji_text and any(
        key in order_context for key in ["取消中", "取消订单", "待审核", "审核", "异常中", "取: 1", "取：1"]
    ), (
        f"S-FLOW-037 打手申请取消订单后丸友集未看到取消申请；source_order_no={source_order_no}; "
        f"order_context={order_context[:1200]}; text={wanyouji_text[:1500]}"
    )


@pytest.mark.s_flow_037
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_037_player_cancel_assigned_order(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    store = account_store()
    order = resolve_order_for_case(
        case_id="S-FLOW-037",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_states=["assigned_player_pending_accept", "player_sub_order_in_progress"],
    )
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-037 使用的打手代练中指派订单；请先执行 S-FLOW-079。")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    reason = os.getenv("E2E_S_FLOW_PLAYER_CANCEL_REASON", f"S-FLOW-037 打手发起取消订单 {main_order_no or source_order_no}")
    wanyouji_account = resolve_wanyouji_account(order)
    player_account = resolve_player_account(order, wanyouji_account)

    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_order_no = os.getenv("E2E_ASSIGNED_PLAYER_ORDER_NO", order.get("assigned_player_sub_order_no", "")).strip()
    if order.get("current_flow_state") == "assigned_player_pending_accept":
        assert assigned_order_no, f"S-FLOW-037 指派单待接单取消缺少打手订单号；order={order}"
        player_text = player_page.apply_cancel_assigned_order_from_player_hall(
            assigned_order_no=assigned_order_no,
            source_order_no=source_order_no,
            order_title=order_title,
            reason=reason,
        )
    else:
        player_text = player_page.apply_player_cancel_order_from_my_orders(source_order_no, order_title, reason)
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"S-FLOW-037 打手代练中发起取消订单：{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_wanyouji_cancel_apply_visible(wanyouji_text, source_order_no, order_title)

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-037",
        status="player_cancel_pending",
        current_flow_state="player_cancel_pending_at_wanyouji",
        task_player_phone=player_account.phone,
        task_wanyouji_phone=wanyouji_account.phone,
        player_cancel_reason=reason,
        player_cancel_apply_text=player_text[:1500],
        wanyouji_after_player_cancel_apply_text=wanyouji_text[:1500],
        wanyouji_sub_order_status="取消中",
        available_for_cases=["S-FLOW-038", "S-FLOW-039"],
    )
