from __future__ import annotations

import os
from typing import Iterable

from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import find_player_account
from e2e.utils.account_store import E2EAccount, account_store


def resolve_order_for_case(
    *,
    case_id: str,
    wanzhanggui_phone: str,
    current_flow_states: Iterable[str] | None = None,
) -> 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

    states = list(current_flow_states or [])
    for state in states:
        candidate = account_store().find_order_for_flow_case(
            case_id=case_id,
            wanzhanggui_phone=wanzhanggui_phone,
            current_flow_state=state,
        )
        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 case_id in item.get("available_for_cases", [])
        and case_id not in item.get("consumed_by_cases", [])
        and (not states or item.get("current_flow_state") in states)
    ]
    return sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0] if candidates else None


def resolve_wanyouji_account(order: dict) -> E2EAccount:
    explicit = os.getenv("E2E_ORDER_WANYOUJI_PHONE", "").strip()
    phone = explicit or order.get("task_wanyouji_phone", "")
    if not phone:
        phones = order.get("wanyouji_phones") or []
        assert phones, f"订单台账缺少丸友集账号；order={order}"
        phone = phones[0]
    account = account_store().find(phone=phone)
    assert account is not None, f"台账中未找到丸友集账号：{phone}"
    return account


def resolve_player_account(order: dict, wanyouji_account: E2EAccount) -> E2EAccount:
    explicit = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip() or os.getenv("E2E_PLAYER_PHONE", "").strip()
    phone = explicit or order.get("task_player_phone", "") or order.get("player_phone", "")
    if phone:
        account = account_store().find(phone=phone)
        assert account is not None, f"台账中未找到打手账号：{phone}"
        return account
    account = find_player_account(wanyouji_account)
    assert account is not None, (
        f"未找到丸友集账号 {wanyouji_account.phone} 下可用打手账号；"
        "可通过 E2E_TASK_PLAYER_PHONE 指定。"
    )
    return account
