from __future__ import annotations

import os

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage, WanzhangguiOrderPage
from e2e.utils.account_store import account_store


APPROVED_KEYWORDS = ["已处理", "已完成", "同意", "赔偿", "处罚", "处理完成", "已赔偿"]
REJECTED_KEYWORDS = ["已处理", "已完成", "驳回", "拒绝", "处罚", "被驳回", "已拒绝"]


def run_penalty_approve_case(
    page: Page,
    settings,
    bug_reporter,
    *,
    case_id: str,
    prerequisite_case_id: str,
    pending_flow_state: str,
    final_status: str,
    final_flow_state: str,
    remark_prefix: str,
    approved_text_field: str,
    approved_record_field: str,
) -> 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_penalty_order(wanzhanggui_phone, case_id=case_id, pending_flow_state=pending_flow_state)
    if not order:
        pytest.skip(f"台账中未找到可供 {case_id} 使用的处罚待处理记录；请先执行 {prerequisite_case_id}")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    wanyouji_account = resolve_wanyouji_account(order)
    remark = f"{case_id} {remark_prefix} {main_order_no or source_order_no}"

    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    bug_reporter.record_if_errors(account=wanyouji_account.phone, location=f"{case_id} 丸友集账号登录")
    approve_text = fulfillment_page.approve_penalty_from_workshop(
        source_order_no,
        order_title,
        remark=remark,
        upstream_order_no=main_order_no,
    )
    assert any(key in approve_text for key in [*APPROVED_KEYWORDS, main_order_no, source_order_no, order_title]), (
        f"{case_id} 同意处罚后未看到处理结果；source_order_no={source_order_no}; text={approve_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"{case_id} 丸友集同意处罚/赔偿：{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)
    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=APPROVED_KEYWORDS,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"{case_id} 丸掌柜子单处罚单回读同意赔偿结果：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id=case_id,
        status=final_status,
        current_flow_state=final_flow_state,
        penalty_approved_by=wanyouji_account.phone,
        penalty_approve_remark=remark,
        **{
            approved_text_field: approve_text[:1500],
            approved_record_field: penalty_record_text[:1500],
        },
        available_for_cases=[],
    )


def run_penalty_reject_case(
    page: Page,
    settings,
    bug_reporter,
    *,
    case_id: str,
    prerequisite_case_id: str,
    pending_flow_state: str,
    final_status: str,
    final_flow_state: str,
    remark_prefix: str,
    rejected_text_field: str,
    rejected_record_field: str,
) -> 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_penalty_order(wanzhanggui_phone, case_id=case_id, pending_flow_state=pending_flow_state)
    if not order:
        pytest.skip(f"台账中未找到可供 {case_id} 使用的处罚待处理记录；请先执行 {prerequisite_case_id}")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    wanyouji_account = resolve_wanyouji_account(order)
    reject_reason = f"{case_id} {remark_prefix} {main_order_no or source_order_no}"

    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    bug_reporter.record_if_errors(account=wanyouji_account.phone, location=f"{case_id} 丸友集账号登录")
    reject_text = fulfillment_page.reject_penalty_from_workshop(
        source_order_no,
        order_title,
        remark=reject_reason,
        upstream_order_no=main_order_no,
    )
    assert any(key in reject_text for key in [*REJECTED_KEYWORDS, main_order_no, source_order_no, order_title]), (
        f"{case_id} 驳回处罚后未看到处理结果；source_order_no={source_order_no}; text={reject_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"{case_id} 丸友集驳回处罚：{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)
    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=REJECTED_KEYWORDS,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"{case_id} 丸掌柜子单处罚单回读驳回结果：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id=case_id,
        status=final_status,
        current_flow_state=final_flow_state,
        penalty_rejected_by=wanyouji_account.phone,
        penalty_reject_reason=reject_reason,
        **{
            rejected_text_field: reject_text[:1500],
            rejected_record_field: penalty_record_text[:1500],
        },
        available_for_cases=[],
    )


def resolve_penalty_order(wanzhanggui_phone: str, *, case_id: str, pending_flow_state: 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=case_id,
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state=pending_flow_state,
    )
    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 item.get("current_flow_state") == pending_flow_state
        and case_id in item.get("available_for_cases", [])
        and case_id 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


def resolve_wanyouji_phone(order: dict) -> str:
    explicit = os.getenv("E2E_ORDER_WANYOUJI_PHONE", "").strip()
    if explicit:
        return explicit
    phones = order.get("wanyouji_phones") or []
    assert phones, f"处罚处理订单台账缺少 wanyouji_phones：{order}"
    return phones[0]


def resolve_wanyouji_account(order: dict):
    phone = resolve_wanyouji_phone(order)
    account = account_store().find(phone=phone)
    assert account is not None, f"台账中未找到丸友集账号：{phone}"
    return account
