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.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    find_player_account,
    login_player_sub_account_by_sms,
)
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_049
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_049_complete_upstream_acceptance(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)
    expected_amount = os.getenv("E2E_DELIVERY_EXPECTED_PLAYER_AMOUNT", "70")

    store = account_store()
    order = resolve_s_flow_049_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-049 使用的待上游验收订单；请先执行 S-FLOW-045。")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", 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-049 丸掌柜账号登录")

    before_detail_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_sub_order_list_status=["待验收", "已完成"],
        expected_aftersale_absent=True,
    )
    completed_text = order_page.complete_upstream_order(source_order_no, order_title)
    assert not order_page.has_unfinished_sub_order_notice(completed_text), (
        f"S-FLOW-049 丸掌柜同意验收时提示仍有未完成子单；source_order_no={source_order_no}; text={completed_text[:1500]}"
    )
    assert any(key in completed_text for key in ["已完成", "完成", "已完结", "完结"]), (
        f"S-FLOW-049 丸掌柜同意验收后未看到完成态；source_order_no={source_order_no}; text={completed_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-049 丸掌柜同意验收/完结主单：{main_order_no or source_order_no}",
    )

    wanyouji_phone = os.getenv("E2E_ORDER_WANYOUJI_PHONE", order.get("task_wanyouji_phone") or (order.get("wanyouji_phones") or [""])[0])
    wanyouji_account = store.find(phone=wanyouji_phone)
    assert wanyouji_account is not None, f"S-FLOW-049 台账中未找到丸友集账号：{wanyouji_phone}"
    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    wanyouji_text = fulfillment_page.search_workshop_order_list(
        fulfillment_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    assert source_order_no in wanyouji_text or order_title in wanyouji_text, (
        f"S-FLOW-049 丸友集订单列表未找到验收完成订单；source_order_no={source_order_no}; text={wanyouji_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-049 丸友集订单列表完成态回查：{main_order_no or source_order_no}",
    )

    player_account = resolve_player_account(order, wanyouji_account)
    player_income_text = ""
    if player_account:
        player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
        player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
        player_income_text = player_page.verify_player_income_for_order(
            source_order_no,
            order_title,
            expected_amount=expected_amount,
        )
        bug_reporter.record_if_errors(
            account=player_account.phone,
            location=f"S-FLOW-049 打手收入验收后复核：{source_order_no}/{order_title}",
        )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-049",
        status="upstream_completed",
        current_flow_state="wanzhanggui_upstream_acceptance_completed",
        upstream_completed_by=wanzhanggui_phone,
        wanzhanggui_before_upstream_complete_detail_text=before_detail_text[:1500],
        wanzhanggui_after_upstream_complete_text=completed_text[:1500],
        wanyouji_after_upstream_complete_text=wanyouji_text[:1500],
        player_income_after_upstream_complete_text=player_income_text[:1500] if isinstance(player_income_text, str) else "",
        wanzhanggui_main_status="已完成",
        wanzhanggui_sub_order_status="已完成",
        wanyouji_parent_status="已完成",
        available_for_cases=["S-FLOW-050", "S-FLOW-054"],
    )


def resolve_s_flow_049_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-049",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanzhanggui_waiting_upstream_acceptance",
    )
    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("status") == "upstream_acceptance_applied"
        and "S-FLOW-049" 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_player_account(order: dict, wanyouji_account) -> object | None:
    store = account_store()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip()
    if explicit_player_phone:
        return store.find(phone=explicit_player_phone)
    if order.get("task_player_phone"):
        account = store.find(phone=order["task_player_phone"])
        if account:
            return account
    return find_player_account(wanyouji_account)
