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.utils.account_store import account_store


@pytest.mark.s_flow_013
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_013_reject_upstream_order_from_hall(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_013_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-013 使用的丸友集待接单订单；请先执行 S-FLOW-005")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    strategy_type = order.get("strategy_type") or os.getenv("E2E_ORDER_STRATEGY_TYPE", "单平台指定")
    expected_scope = "私单" if strategy_type == "单平台指定" else "公池单/私单"
    wanyouji_phone = resolve_wanyouji_phone(order)
    wanyouji_account = store.find(phone=wanyouji_phone)
    assert wanyouji_account is not None, f"台账中未找到 S-FLOW-013 丸友集账号：{wanyouji_phone}"
    reject_reason = os.getenv(
        "E2E_S_FLOW_REJECT_REASON",
        f"S-FLOW-013 丸友集拒绝上游订单 {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)
    bug_reporter.record_if_errors(account=wanyouji_account.phone, location="S-FLOW-013 丸友集账号登录")

    rejected_hall_text = fulfillment_page.reject_external_order_from_hall(
        source_order_no=source_order_no,
        order_title=order_title,
        expected_scope=expected_scope,
        main_order_no=main_order_no,
        reject_reason=reject_reason,
        manual_reject=os.getenv("E2E_S_FLOW_013_MANUAL_REJECT", "").strip() in {"1", "true", "yes"},
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-013 丸友集抢单大厅拒绝上游订单：{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)
    bug_reporter.record_if_errors(account=wanzhanggui_phone, location="S-FLOW-013 丸掌柜账号登录")

    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-013 丸掌柜订单详情拒绝结果状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-013",
        status="wanyouji_rejected",
        current_flow_state="wanyouji_rejected_upstream_order",
        wanyouji_rejected_by=wanyouji_account.phone,
        wanyouji_reject_reason=reject_reason,
        wanyouji_before_reject_hall_text="see reject flow source-order exact query",
        wanyouji_rejected_hall_text=rejected_hall_text[:1500],
        wanzhanggui_rejected_detail_status_text=detail_status_text[:1500],
        wanyouji_visibility="rejected_or_hall_hidden",
        available_for_cases=[],
    )


def resolve_s_flow_013_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()
    payload = account_store().load_payload()
    if explicit_main_order_no or explicit_source_order_no:
        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

    probe_source_order_nos = [
        item.strip()
        for item in os.getenv(
            "E2E_S_FLOW_013_PROBE_SOURCE_ORDER_NOS",
            "E2EORDER0616113610,E2EORDER0616113406,E2EORDER0622162306",
        ).split(",")
        if item.strip()
    ]
    for source_order_no in probe_source_order_nos:
        for item in payload.get("dispatched_orders", []):
            if wanzhanggui_phone and item.get("wanzhanggui_phone") != wanzhanggui_phone:
                continue
            if item.get("source_order_no") == source_order_no:
                return item

    candidate = account_store().find_order_for_flow_case(
        case_id="S-FLOW-013",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanyouji_pending_accept_rejectable",
    )
    if candidate:
        return candidate
    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if (not wanzhanggui_phone or item.get("wanzhanggui_phone") == wanzhanggui_phone)
        and item.get("status") == "dispatched"
        and item.get("current_flow_state") == "wanyouji_pending_accept_rejectable"
        and "S-FLOW-013" not in item.get("consumed_by_cases", [])
    ]
    if candidates:
        return sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0]
    return None


def resolve_wanyouji_phone(order: dict) -> str:
    explicit = os.getenv("E2E_ORDER_WANYOUJI_PHONE", "").strip()
    if explicit:
        return explicit
    phones = order.get("wanyouji_phones") or []
    assert phones, f"S-FLOW-013 订单台账缺少 wanyouji_phones；order={order}"
    return phones[0]
