from __future__ import annotations

import os
from collections.abc import Callable
from dataclasses import dataclass

import pytest
from playwright.sync_api import Page

from e2e.tests.履约验收.test_e2e_delivery_001_player_submit_acceptance import (
    test_打手确认上号上传首图并提交验收后主账号查看 as run_delivery_001,
)
from e2e.tests.履约验收.test_e2e_delivery_002_upstream_acceptance_settlement import (
    test_丸友集验收打手子单并校验打手收入 as run_delivery_002,
)
from e2e.tests.订单流转.test_e2e_order_001_manual_order_dispatch_closed_loop import (
    test_丸掌柜手工录单发单并在丸友集抢单大厅验证闭环 as run_order_001,
)
from e2e.tests.结算.test_e2e_settle_player_account_001_payment_account import (
    test_打手完善打款账户信息 as run_settle_player_account_001,
)
from e2e.tests.结算.test_e2e_settle_player_apply_001_create_bill import (
    test_打手在我的收入中点击一键结算并提交账单 as run_settle_player_apply_001,
)
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    test_丸掌柜外部派单由丸友集接单并发到打手抢单大厅 as run_task_001,
)


FIXED_WANZHANGGUI_PHONE = "19147509308"
FIXED_WANZHANGGUI_PASSWORD = "test123456"


def run_stage(
    page: Page,
    stage_id: str,
    description: str,
    action: Callable[[], None],
    *,
    reset_page: bool = False,
) -> None:
    print("")
    print(f"[E2E-MAIN-002] start {stage_id}: {description}")
    if reset_page:
        isolate_page(page)
    action()
    print(f"[E2E-MAIN-002] done {stage_id}: {description}")


def isolate_page(page: Page) -> None:
    try:
        page.goto("about:blank", wait_until="domcontentloaded")
        page.wait_for_timeout(500)
    except Exception:
        pass


@dataclass(frozen=True)
class MainStage:
    stage_id: str
    description: str
    action: Callable[[], None]


@pytest.mark.e2e_main_002
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_主流程_丸掌柜发单到打手_打手正常完成订单并提交结算账单(
    page: Page,
    settings,
    bug_reporter,
    monkeypatch,
) -> None:
    monkeypatch.setenv("E2E_ORDER_WANZHANGGUI_PHONE", FIXED_WANZHANGGUI_PHONE)
    monkeypatch.setenv("E2E_ORDER_WANZHANGGUI_PASSWORD", FIXED_WANZHANGGUI_PASSWORD)
    monkeypatch.setenv("E2E_TASK_WANZHANGGUI_PHONE", FIXED_WANZHANGGUI_PHONE)
    monkeypatch.setenv("E2E_TASK_ASSIGNMENT_METHOD", os.getenv("E2E_MAIN_002_ASSIGNMENT_METHOD", "抢单大厅"))
    monkeypatch.setenv("E2E_ORDER_MODE", "手工录单")
    monkeypatch.setenv("E2E_REUSE_TENANT_LOGIN", "1")
    monkeypatch.setenv("E2E_REUSE_PLAYER_LOGIN", "1")
    monkeypatch.setenv("E2E_SETTLE_PLAYER_APPLY_SKIP_OWNER_SUMMARY", "1")
    monkeypatch.setenv("E2E_PLAYER_SETTLEMENT_FAST_SEARCH", "1")

    strategy_type = os.getenv("E2E_MAIN_002_STRATEGY_TYPE", os.getenv("E2E_ORDER_STRATEGY_TYPE", "单平台指定"))
    monkeypatch.setenv("E2E_ORDER_STRATEGY_TYPE", strategy_type)
    monkeypatch.setenv("E2E_TASK_STRATEGY_TYPE", strategy_type)

    print("")
    print("[E2E-MAIN-002] main flow: order -> task -> delivery -> owner acceptance -> player settlement apply")
    print(f"[E2E-MAIN-002] wanzhanggui={FIXED_WANZHANGGUI_PHONE}; strategy_type={strategy_type}")

    stages = [
        MainStage("ORDER-001", "丸掌柜手工录单并发布外部订单到丸友集", lambda: run_order_001(page, settings, bug_reporter)),
        MainStage("TASK-001", "丸友集确认外部订单并发给打手，打手接单", lambda: run_task_001(page, settings, bug_reporter)),
        MainStage("DELIVERY-001", "打手确认上号、上传首图并提交验收", lambda: run_delivery_001(page, settings, bug_reporter)),
        MainStage("DELIVERY-002", "丸友集确认验收打手子单并校验打手收入", lambda: run_delivery_002(page, settings, bug_reporter)),
        MainStage("SETTLE-PLAYER-ACCOUNT-001", "确认打手打款账户可用于一键结算", lambda: run_settle_player_account_001(page, settings, bug_reporter)),
        MainStage("SETTLE-PLAYER-APPLY-001", "打手在我的收入中提交结算账单", lambda: run_settle_player_apply_001(page, settings, bug_reporter)),
    ]

    start_stage = os.getenv("E2E_MAIN_002_START_STAGE", "ORDER-001").strip()
    stage_ids = [stage.stage_id for stage in stages]
    assert start_stage in stage_ids, f"E2E_MAIN_002_START_STAGE 仅支持：{', '.join(stage_ids)}；当前值：{start_stage}"
    if start_stage != "ORDER-001":
        print(f"[E2E-MAIN-002] resume from stage: {start_stage}")

    for stage in stages[stage_ids.index(start_stage) :]:
        run_stage(page, stage.stage_id, stage.description, stage.action)

    print("[E2E-MAIN-002] main flow complete")
