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
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.e2e_delivery_002
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_丸友集验收打手子单并校验打手收入(page: Page, settings, bug_reporter) -> None:
    store = account_store()
    order, wanyouji_account, player_account = resolve_delivery_002_order_and_accounts()
    source_order_no = order["source_order_no"]
    order_title = order["order_title"]
    expected_amount = os.getenv("E2E_DELIVERY_EXPECTED_PLAYER_AMOUNT", "70")

    owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    owner_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    owner_page.accept_sub_order_and_verify_ready_for_upstream(source_order_no, order_title)
    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="sub_order_accepted",
        sub_order_accepted_by=wanyouji_account.phone,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"丸友集主账号-工作室履约应用-订单列表-同意验收子单：{source_order_no}/{order_title}",
    )

    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_page.verify_player_income_for_order(source_order_no, order_title, expected_amount=expected_amount)
    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="sub_order_income_verified",
        settlement_verified_by=player_account.phone,
        expected_player_amount=expected_amount,
    )
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"丸友集打手账号-打手应用-我的收入-校验子单收入：{source_order_no}/{order_title}",
    )


def resolve_delivery_002_order_and_accounts() -> tuple[dict[str, Any], E2EAccount, E2EAccount]:
    store = account_store()
    payload = store.load_payload()
    explicit_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "").strip()
    explicit_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"}
    if explicit_order_no:
        allowed_statuses.update({"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)
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    assert candidates, "台账中没有可用于 E2E-DELIVERY-002 的已提交验收订单，请先执行 E2E-DELIVERY-001。"

    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("未找到 DELIVERY-002 可用的丸友集主账号和打手账号组合。")
