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_s_flow_038_accept_player_sub_order import (
    resolve_s_flow_038_order_and_accounts,
)
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_045
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_045_apply_upstream_acceptance(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_045_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-045 使用的已完成子单；请先执行 S-FLOW-043。")

    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 = os.getenv("E2E_ORDER_WANYOUJI_PHONE", order.get("task_wanyouji_phone") or (order.get("wanyouji_phones") or [""])[0])
    wanyouji_account = store.find(phone=wanyouji_phone)
    assert wanyouji_account is not None, f"S-FLOW-045 台账中未找到丸友集账号：{wanyouji_phone}"

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

    before_text = fulfillment_page.search_workshop_order_list(
        fulfillment_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    assert source_order_no in before_text or order_title in before_text, (
        f"S-FLOW-045 丸友集订单列表未找到目标订单；source_order_no={source_order_no}; text={before_text[:1500]}"
    )

    applied_text = fulfillment_page.apply_upstream_acceptance(source_order_no, order_title)
    assert any(key in applied_text for key in ["等待上游验收", "待验收", "申请验收时间", "已完成"]), (
        f"S-FLOW-045 申请上游验收后未看到待上游验收状态；source_order_no={source_order_no}; text={applied_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-045 丸友集申请上游验收：{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)
    detail_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=["待验收", "已完成", "代练中"],
        expected_sub_order_list_status=["待验收", "已完成"],
        expected_aftersale_absent=True,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-045 丸掌柜订单详情待验收状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-045",
        status="upstream_acceptance_applied",
        current_flow_state="wanzhanggui_waiting_upstream_acceptance",
        upstream_acceptance_applied_by=wanyouji_account.phone,
        wanyouji_before_upstream_acceptance_text=before_text[:1500],
        wanyouji_after_upstream_acceptance_text=applied_text[:1500],
        wanzhanggui_waiting_upstream_acceptance_detail_text=detail_text[:1500],
        wanyouji_parent_status="等待上游验收",
        wanzhanggui_main_status="待验收",
        wanzhanggui_sub_order_status="待验收",
        available_for_cases=["S-FLOW-082", "S-FLOW-046", "S-FLOW-049"],
    )


def resolve_s_flow_045_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

    candidate = account_store().find_order_for_flow_case(
        case_id="S-FLOW-045",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanyouji_sub_order_accepted_ready_for_upstream",
    )
    if candidate:
        return candidate
    try:
        order, _, _ = resolve_s_flow_038_order_and_accounts()
        if not wanzhanggui_phone or order.get("wanzhanggui_phone") == wanzhanggui_phone:
            return order
    except pytest.skip.Exception:
        return None
    return None
