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_051
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_051_start_appeal_from_aftersale_completed(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_051_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-051 使用的已售后订单，请先执行 FLOW-001 到 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)
    appeal_amount = os.getenv("E2E_S_FLOW_APPEAL_AMOUNT", "1")
    appeal_reason = f"S-FLOW-051 已售后发起申诉 {main_order_no or source_order_no}"

    assert order.get("current_flow_state") in {
        "wanzhanggui_aftersale_completed",
        "wanyouji_sub_order_aftersale_approved",
    }, (
        f"S-FLOW-051 前置台账状态不满足已售后；order={order}"
    )
    assert order.get("status") in {
        "aftersale_completed",
        "sub_order_aftersale_approved",
    }, f"S-FLOW-051 前置业务状态不满足已售后；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-051 丸掌柜账号登录")

    final_text = order_page.start_appeal_for_order(
        source_order_no,
        order_title,
        main_order_no=main_order_no,
        reason=appeal_reason,
        amount=appeal_amount,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-051 丸掌柜-已售后订单发起申诉：{main_order_no or source_order_no}/{order_title}",
    )
    appeal_record_text = order_page.assert_main_order_appeal_record_visible(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        reason=appeal_reason,
        amount=appeal_amount,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-051 丸掌柜-主单申诉单记录校验：{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_appeal_status=["处理中", "申诉中"],
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-051 丸掌柜订单详情状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-051",
        status="appeal_pending_from_aftersale",
        current_flow_state="wanzhanggui_appeal_pending_from_aftersale_completed",
        wanzhanggui_main_status="已售后",
        wanzhanggui_sub_order_status="已售后-申诉中",
        appeal_started_by=wanzhanggui_phone,
        appeal_reason=appeal_reason,
        appeal_amount=appeal_amount,
        appeal_started_text=final_text[:1500],
        appeal_record_text=appeal_record_text[:1500],
        appeal_started_detail_status_text=detail_status_text[:1500],
        available_for_cases=["S-FLOW-052", "S-FLOW-053"],
    )


def resolve_s_flow_051_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 item.get("current_flow_state") in {
                "wanzhanggui_aftersale_completed",
                "wanyouji_sub_order_aftersale_approved",
            }:
                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 item.get("status") in {"aftersale_completed", "sub_order_aftersale_approved"}
        and item.get("current_flow_state") in {
            "wanzhanggui_aftersale_completed",
            "wanyouji_sub_order_aftersale_approved",
        }
        and (
            item.get("current_flow_state") == "wanzhanggui_aftersale_completed"
            or "S-FLOW-051" in item.get("available_for_cases", [])
        )
        and "S-FLOW-051" not in item.get("consumed_by_cases", [])
    ]
    if reusable_orders:
        return sorted(reusable_orders, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0]
    return None
