from __future__ import annotations

import os
import re

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_053
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_053_reject_main_order_appeal(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_053_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-053 使用的主单申诉待处理订单，请先执行 S-FLOW-051")

    source_order_no = order["source_order_no"]
    main_order_no = resolve_main_order_no(order)
    order_title = order.get("order_title", source_order_no)
    reject_reason = f"S-FLOW-053 主单申诉审核驳回 {main_order_no or source_order_no}"

    assert order.get("status") == "appeal_pending_from_aftersale", f"S-FLOW-053 前置业务状态不满足；order={order}"
    assert order.get("current_flow_state") == "wanzhanggui_appeal_pending_from_aftersale_completed", (
        f"S-FLOW-053 前置台账状态不满足；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-053 丸掌柜账号登录")

    if not main_order_no:
        main_order_no = order_page.find_main_order_no_from_order_list(source_order_no=source_order_no, order_title=order_title)
        reject_reason = f"S-FLOW-053 主单申诉审核驳回 {main_order_no}"

    rejection_text = order_page.reject_main_order_appeal(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        reject_reason=reject_reason,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-053 丸掌柜-主单申诉单审核驳回：{main_order_no}/{source_order_no}",
    )

    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=["已完成→申诉完成", "已售后→申诉完成"],
        expected_appeal_status="已拒绝",
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-053 丸掌柜订单详情状态校验：{main_order_no}/{source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-053",
        main_order_no=main_order_no,
        status="appeal_rejected_from_aftersale",
        current_flow_state="wanzhanggui_main_appeal_rejected_from_aftersale_completed",
        wanzhanggui_main_status="已完成",
        wanzhanggui_sub_order_status="已售后-申诉完成",
        appeal_rejected_by=wanzhanggui_phone,
        appeal_rejected_reason=reject_reason,
        appeal_rejected_text=rejection_text[:1500],
        appeal_rejected_detail_status_text=detail_status_text[:1500],
        available_for_cases=[],
    )


def resolve_s_flow_053_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_source_order_no and item.get("source_order_no") != explicit_source_order_no:
                continue
            if explicit_main_order_no and resolve_main_order_no(item) != explicit_main_order_no:
                continue
            if "S-FLOW-053" in item.get("available_for_cases", []) and "S-FLOW-053" not in item.get("consumed_by_cases", []):
                return item
        if explicit_main_order_no.startswith("BO"):
            return {
                "wanzhanggui_phone": wanzhanggui_phone,
                "main_order_no": explicit_main_order_no,
                "source_order_no": explicit_source_order_no or explicit_main_order_no,
                "order_title": explicit_source_order_no or explicit_main_order_no,
                "status": "appeal_pending_from_aftersale",
                "current_flow_state": "wanzhanggui_appeal_pending_from_aftersale_completed",
                "available_for_cases": ["S-FLOW-053"],
                "consumed_by_cases": [],
                "probe_main_order_only": True,
            }
        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") == "appeal_pending_from_aftersale"
        and item.get("current_flow_state") == "wanzhanggui_appeal_pending_from_aftersale_completed"
        and "S-FLOW-053" in item.get("available_for_cases", [])
        and "S-FLOW-053" 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


def resolve_main_order_no(order: dict) -> str:
    if order.get("main_order_no", "").startswith("BO"):
        return order["main_order_no"]
    for key in ["appeal_record_text", "appeal_started_text", "aftersale_processed_text"]:
        value = order.get(key) or ""
        match = re.search(r"BO\d{20}", value)
        if match:
            return match.group(0)
    return ""
