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_052
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_052_approve_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_052_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-052 使用的主单申诉待处理订单，请先执行 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)
    compensation_amount = os.getenv("E2E_S_FLOW_APPEAL_COMPENSATION_AMOUNT", order.get("appeal_amount", "1"))
    audit_remark = f"S-FLOW-052 主单申诉审核通过 {main_order_no or source_order_no}"

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

    approval_text = order_page.approve_main_order_appeal(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        compensation_amount=compensation_amount,
        remark=audit_remark,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-052 丸掌柜-主单申诉单审核通过：{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-052 丸掌柜订单详情状态校验：{main_order_no}/{source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-052",
        main_order_no=main_order_no,
        status="appeal_approved_from_aftersale",
        current_flow_state="wanzhanggui_main_appeal_approved_from_aftersale_completed",
        wanzhanggui_main_status="已完成",
        wanzhanggui_sub_order_status="已售后-申诉完成",
        appeal_approved_by=wanzhanggui_phone,
        appeal_approved_amount=compensation_amount,
        appeal_approved_remark=audit_remark,
        appeal_approved_text=approval_text[:1500],
        appeal_approved_detail_status_text=detail_status_text[:1500],
        available_for_cases=[],
    )


def resolve_s_flow_052_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-052" in item.get("available_for_cases", []) and "S-FLOW-052" not in item.get("consumed_by_cases", []):
                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") == "appeal_pending_from_aftersale"
        and item.get("current_flow_state") == "wanzhanggui_appeal_pending_from_aftersale_completed"
        and "S-FLOW-052" in item.get("available_for_cases", [])
        and "S-FLOW-052" 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"]:
        match = re.search(r"BO\d{20}", order.get(key, ""))
        if match:
            return match.group(0)
    return ""
