from __future__ import annotations

import os

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 login_player_sub_account_by_sms
from e2e.utils.account_store import E2EAccount, account_store


@pytest.mark.e2e_settle_wanyouji_pay_001
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_单独校验丸友集打款后打手我的收入状态已同步(page: Page, settings, bug_reporter) -> None:
    order, player_account = resolve_completed_player_income_order()
    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_settlement_completed(
        order["source_order_no"],
        order["order_title"],
        expected_amount=os.getenv("E2E_DELIVERY_EXPECTED_PLAYER_AMOUNT", order.get("expected_player_amount", "70")),
        expected_total_amount=os.getenv(
            "E2E_PLAYER_SETTLEMENT_EXPECTED_TOTAL_AMOUNT",
            order.get("wanyouji_player_settlement_total_amount", "280"),
        ),
    )


def resolve_completed_player_income_order() -> tuple[dict, E2EAccount]:
    explicit_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "").strip()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip() or os.getenv("E2E_PLAYER_PHONE", "").strip()
    store = account_store()
    payload = store.load_payload()
    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if item.get("status") == "player_settlement_completed"
        and item.get("task_player_phone")
        and (not explicit_order_no or item.get("source_order_no") == explicit_order_no)
        and (not explicit_player_phone or item.get("task_player_phone") == explicit_player_phone)
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    assert candidates, "台账中没有已完成丸友集给打手结算的订单，请先执行B-SETTLE-WANYOUJI-PAY-001线下支付分支。"
    accounts = {account.phone: account for account in store.load()}
    order = candidates[0]
    player = accounts.get(order.get("task_player_phone", ""))
    assert player, f"台账中未找到打手账号：{order.get('task_player_phone', '')}"
    return order, player
