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_050
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_050_start_appeal_from_completed_order(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_050_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-050 使用的已完成订单；请先执行 S-FLOW-049。")

    source_order_no = order["source_order_no"]
    main_order_no = resolve_main_order_no(order)
    order_title = order.get("order_title", source_order_no)
    appeal_amount = os.getenv("E2E_S_FLOW_APPEAL_AMOUNT", "1")
    appeal_reason = f"S-FLOW-050 已完成主单发起申诉 {main_order_no or source_order_no}"

    assert order.get("status") == "upstream_completed", f"S-FLOW-050 前置业务状态不满足已完成；order={order}"
    assert order.get("current_flow_state") == "wanzhanggui_upstream_acceptance_completed", (
        f"S-FLOW-050 前置台账状态不满足上游验收完成；order={order}"
    )
    assert "S-FLOW-050" in order.get("available_for_cases", []), f"该订单未声明可用于 S-FLOW-050；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-050 丸掌柜账号登录")

    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)
        appeal_reason = f"S-FLOW-050 已完成主单发起申诉 {main_order_no}"

    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,
        expected_main_status="已完成",
        case_label="S-FLOW-050",
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-050 丸掌柜已完成订单发起主单申诉：{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-050 丸掌柜主单申诉单记录校验：{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-050 丸掌柜订单详情申诉中状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-050",
        main_order_no=main_order_no,
        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_050_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 item.get("status") == "upstream_completed" and "S-FLOW-050" in item.get("available_for_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") == "upstream_completed"
        and item.get("current_flow_state") == "wanzhanggui_upstream_acceptance_completed"
        and "S-FLOW-050" in item.get("available_for_cases", [])
        and "S-FLOW-050" 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 ["wanzhanggui_after_upstream_complete_text", "wanzhanggui_after_upstream_complete_detail_text"]:
        value = order.get(key) or ""
        match = re.search(r"BO\d{20}", value)
        if match:
            return match.group(0)
    return ""
