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_062
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_062_start_penalty_from_aftersale_end(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_062_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-062 使用的售后结束子单；请先执行 S-FLOW-035 或显式指定主单号")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    amount = os.getenv("E2E_S_FLOW_PENALTY_AMOUNT", "1")
    reason = f"S-FLOW-062 对售后结束子单发起处罚 {main_order_no or source_order_no}"

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

    before_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_sub_order_list_status="售后结束",
    )
    assert "处罚" in before_detail_status_text, (
        f"S-FLOW-062 前置售后结束子单未展示处罚入口；main_order_no={main_order_no}; "
        f"source_order_no={source_order_no}; detail={before_detail_status_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-062 丸掌柜发起处罚前售后结束状态校验：{main_order_no or source_order_no}",
    )

    order_page.start_penalty_for_aftersale_ended_sub_order(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        reason=reason,
        amount=amount,
    )
    penalty_record_text = order_page.assert_sub_order_penalty_record_visible(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        expected_status_keywords=["处理中", "待处理", "申诉中", "待赔偿", "待审核", "去处理"],
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-062 丸掌柜子单处罚单回读处罚记录：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-062",
        status="penalty_pending_from_aftersale_end",
        current_flow_state="wanzhanggui_penalty_pending_from_aftersale_end",
        penalty_started_by=wanzhanggui_phone,
        penalty_reason=reason,
        penalty_amount=amount,
        penalty_before_detail_text=before_detail_status_text[:1500],
        penalty_started_text=penalty_record_text[:1500],
        sub_order_penalty_record_text=penalty_record_text[:1500],
        available_for_cases=["S-FLOW-063", "S-FLOW-064"],
    )


def resolve_s_flow_062_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
            return item
        return None

    candidate = account_store().find_order_for_flow_case(
        case_id="S-FLOW-062",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanyouji_abnormal_sub_order_aftersale_approved",
    )
    if candidate:
        return candidate

    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if (not wanzhanggui_phone or item.get("wanzhanggui_phone") == wanzhanggui_phone)
        and "S-FLOW-062" in item.get("available_for_cases", [])
        and "S-FLOW-062" not in item.get("consumed_by_cases", [])
    ]
    return sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0] if candidates else None
