from __future__ import annotations

import os

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanzhangguiOrderPage
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_002
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_002_start_aftersale_from_pending_without_dispatch(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_002_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-002 使用的主单待接单/子单待接单-待推单订单，请先执行 S-FLOW-001")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    aftersale_reason = f"S-FLOW-002 发起售后 {source_order_no}"
    aftersale_amount = os.getenv("E2E_S_FLOW_AFTERSALE_AMOUNT", "1")

    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-002 丸掌柜账号登录")

    final_text = order_page.start_aftersale_for_order(
        source_order_no,
        order_title,
        reason=aftersale_reason,
        amount=aftersale_amount,
        main_order_no=main_order_no,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-002 丸掌柜-主单待接单/子单待推单-发起售后：{source_order_no}/{order_title}",
    )

    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_aftersale_status=["售后中", "处理中", "待处理"],
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-002 丸掌柜订单详情状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-002",
        status="aftersale_pending",
        current_flow_state="wanzhanggui_aftersale_pending_from_without_dispatch",
        wanzhanggui_main_status="售后中",
        wanzhanggui_sub_order_status="售后中",
        aftersale_started_by=wanzhanggui_phone,
        aftersale_reason=aftersale_reason,
        aftersale_amount=aftersale_amount,
        aftersale_started_text=final_text[:1500],
        aftersale_started_detail_status_text=detail_status_text[:1500],
        available_for_cases=["S-FLOW-003", "S-FLOW-004"],
    )


def resolve_s_flow_002_order(wanzhanggui_phone: str) -> dict | None:
    explicit_source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "").strip()
    if explicit_source_order_no:
        for item in account_store().load_payload().get("dispatched_orders", []):
            if item.get("source_order_no") == explicit_source_order_no:
                return item
        return None
    store = account_store()
    reusable_after_cancel = store.find_order_for_flow_case(
        case_id="S-FLOW-002",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanzhanggui_pending_accept_without_sub_order",
    )
    if reusable_after_cancel:
        return reusable_after_cancel
    payload = store.load_payload()
    orders = [
        item
        for item in payload.get("dispatched_orders", [])
        if item.get("wanzhanggui_phone") == wanzhanggui_phone
        and item.get("current_flow_state") == "wanzhanggui_pending_accept_without_sub_order"
        and item.get("status") == "without_dispatch"
        and "S-FLOW-002" in item.get("available_for_cases", [])
    ]
    return sorted(orders, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0] if orders else None
