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_003
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_003_process_aftersale_from_pending(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_003_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-003 使用的主单售后中订单，请先执行任一主单发起售后用例")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    process_amount = os.getenv("E2E_S_FLOW_AFTERSALE_PROCESS_AMOUNT", order.get("aftersale_amount", "1") or "1")
    process_remark = f"S-FLOW-003 主单确认售后 {main_order_no or source_order_no}"

    assert is_main_aftersale_pending_state(order.get("current_flow_state", "")), (
        f"S-FLOW-003 前置台账状态不满足主单售后中；order={order}"
    )
    assert "S-FLOW-003" in order.get("available_for_cases", []), f"该订单未声明可用于 S-FLOW-003；order={order}"

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

    final_text = order_page.process_aftersale_for_order(
        source_order_no,
        order_title,
        main_order_no=main_order_no,
        remark=process_remark,
        amount=process_amount,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-003 丸掌柜-主单售后中订单确认售后：{main_order_no or 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-003 丸掌柜订单详情状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-003",
        status="aftersale_completed",
        current_flow_state="wanzhanggui_aftersale_completed",
        wanzhanggui_main_status="已售后",
        wanzhanggui_sub_order_status="已售后",
        aftersale_processed_by=wanzhanggui_phone,
        aftersale_process_remark=process_remark,
        aftersale_process_amount=process_amount,
        aftersale_processed_text=final_text[:1500],
        aftersale_processed_detail_status_text=detail_status_text[:1500],
        available_for_cases=["S-FLOW-051"],
    )


def resolve_s_flow_003_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
            if is_main_aftersale_pending_state(item.get("current_flow_state", "")):
                return item
        return None
    reusable_orders = [
        item
        for item in payload.get("dispatched_orders", [])
        if (not wanzhanggui_phone or item.get("wanzhanggui_phone") == wanzhanggui_phone)
        and is_main_aftersale_pending_state(item.get("current_flow_state", ""))
        and "S-FLOW-003" in item.get("available_for_cases", [])
    ]
    if reusable_orders:
        return sorted(reusable_orders, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0]
    return None


def is_main_aftersale_pending_state(state: str) -> bool:
    return state.startswith("wanzhanggui_aftersale_pending") or state == "wanzhanggui_abnormal_main_order_aftersale_pending"
