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_player_account_001
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_打手完善打款账户信息(page: Page, settings, bug_reporter) -> None:
    store = account_store()
    player_account = resolve_player_account_for_payment()

    login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
    player_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    player_page.ensure_player_payment_account_ready(
        account_name=os.getenv("E2E_PLAYER_PAYMENT_ACCOUNT_NAME", player_account.contact_name or "E2E打手"),
        account_phone=os.getenv("E2E_PLAYER_PAYMENT_ACCOUNT_PHONE", player_account.phone),
        payment_account=os.getenv("E2E_PLAYER_PAYMENT_ACCOUNT_NO", f"e2e{player_account.phone}@example.com"),
        bank_name=os.getenv("E2E_PLAYER_PAYMENT_BANK_NAME", "E2E测试银行"),
        id_card=os.getenv("E2E_PLAYER_PAYMENT_ID_CARD", "110101199001011234"),
    )
    store.upsert(
        player_account,
        player_payment_account_status="ready",
        player_payment_account_verified_by=player_account.phone,
    )
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"丸友集打手账号-打手应用-我的收入-完善打款账户信息：{player_account.phone}",
    )


def resolve_player_account_for_payment() -> E2EAccount:
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip() or os.getenv("E2E_PLAYER_PHONE", "").strip()
    candidates = [
        account
        for account in account_store().load()
        if account.account_type == "sub"
        and (not explicit_player_phone or account.phone == explicit_player_phone)
        and account.member_status in {"approved", "registered"}
        and ("打手" in account.member_role or "打手" in account.contact_name or account.member_role.lower() == "player")
    ]
    candidates = sorted(candidates, key=lambda account: account.updated_at, reverse=True)
    assert candidates, "台账中没有可用于 B-SETTLE-PLAYER-ACCOUNT-001 的打手子账号。"
    return candidates[0]
