from __future__ import annotations

import os
from typing import Any

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 E2EAccount, account_store


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

    store = account_store()
    order, wanyouji_account, player_account = resolve_s_flow_038_order_and_accounts()
    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)

    owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    owner_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    bug_reporter.record_if_errors(account=wanyouji_account.phone, location="S-FLOW-038 丸友集账号登录")

    before_text = owner_page.search_workshop_order_list(
        owner_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    assert "待验收" in before_text or "验:" in before_text or "申请上游验收" in before_text, (
        f"S-FLOW-038 前置不满足打手/子单待验收；source_order_no={source_order_no}; text={before_text[:1500]}"
    )

    accepted_text = owner_page.accept_sub_order_and_verify_ready_for_upstream(source_order_no, order_title)
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-038 丸友集同意验收打手子单：{main_order_no or source_order_no}",
    )

    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)
    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-038 打手我的收入校验：{source_order_no}/{order_title}",
    )

    order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, bug_reporter)
    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    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_parts=["代练中", "服务中", "待验收", "已完成"],
        expected_sub_order_list_status=["已完成", "待验收", "服务中", "代练中"],
        expected_aftersale_absent=True,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-038 丸掌柜订单详情验收后状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-038",
        status="sub_order_income_verified",
        current_flow_state="wanyouji_sub_order_accepted_ready_for_upstream",
        sub_order_accepted_by=wanyouji_account.phone,
        settlement_verified_by=player_account.phone,
        expected_player_amount=expected_amount,
        wanyouji_before_sub_order_accept_text=before_text[:1500],
        wanyouji_after_sub_order_accept_text=accepted_text[:1500],
        player_income_after_sub_order_accept_text=income_text[:1500] if isinstance(income_text, str) else "",
        wanzhanggui_after_sub_order_accept_detail_text=detail_text[:1500],
        wanyouji_parent_status="已完成",
        wanyouji_sub_order_status="已完成",
        wanzhanggui_main_status="服务中",
        wanzhanggui_sub_order_status="已完成",
        available_for_cases=["S-FLOW-039", "S-FLOW-040", "S-FLOW-054"],
    )


def resolve_s_flow_038_order_and_accounts() -> tuple[dict[str, Any], E2EAccount, E2EAccount]:
    store = account_store()
    payload = store.load_payload()
    explicit_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "")).strip()
    explicit_wanyouji_phone = os.getenv("E2E_ORDER_WANYOUJI_PHONE", os.getenv("E2E_TASK_WANYOUJI_PHONE", "")).strip()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip()
    allowed_statuses = {"delivery_submitted", "sub_order_accepted", "sub_order_income_verified"}

    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if item.get("status") in allowed_statuses
        and item.get("task_player_phone")
        and (item.get("task_wanyouji_phone") or item.get("wanyouji_phones"))
        and (not explicit_order_no or item.get("source_order_no") == explicit_order_no)
        and "S-FLOW-038" not in item.get("consumed_by_cases", [])
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    if not candidates:
        pytest.skip("台账中未找到可供 S-FLOW-038 使用的待验收子单；请先执行打手提交验收流程。")

    accounts = {account.phone: account for account in store.load()}
    for order in candidates:
        wanyouji_phone = explicit_wanyouji_phone or order.get("task_wanyouji_phone") or (order.get("wanyouji_phones") or [""])[0]
        wanyouji_account = accounts.get(wanyouji_phone)
        if not wanyouji_account:
            continue
        player_account = accounts.get(explicit_player_phone or order.get("task_player_phone", ""))
        if not player_account:
            player_account = find_player_account(wanyouji_account, explicit_player_phone)
        if player_account:
            return order, wanyouji_account, player_account

    raise AssertionError("S-FLOW-038 未找到可用的丸友集主账号和打手账号组合。")
