from __future__ import annotations

import os
import random
from datetime import datetime

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import ManualOrderData, WanzhangguiOrderPage
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_001
@pytest.mark.e2e_ledger
@pytest.mark.e2e_standalone
def test_s_flow_001_create_order_without_dispatch(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    wanzhanggui_password = os.getenv("E2E_ORDER_WANZHANGGUI_PASSWORD", settings.wanzhanggui_tenant_password)

    store = account_store()
    wanzhanggui_account = store.find(phone=wanzhanggui_phone)
    assert wanzhanggui_account is not None, f"台账中未找到丸掌柜账号：{wanzhanggui_phone}"
    assert wanzhanggui_account.wanzhanggui_status == "opened", (
        f"账号 {wanzhanggui_phone} 未处于已开通丸掌柜状态，当前状态：{wanzhanggui_account.wanzhanggui_status}"
    )

    order = resolve_without_dispatch_order(wanzhanggui_phone)
    if not should_create_without_dispatch_order(order, wanzhanggui_phone) and not has_reusable_order_identity(order):
        pytest.skip("未找到可复用的 S-FLOW-001 未推单主单；请提供 E2E_S_FLOW_MAIN_ORDER_NO=BO... 后再验证")

    order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, bug_reporter)
    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    bug_reporter.record_if_errors(account=wanzhanggui_phone, location="丸掌柜账号-主账号登录")
    if should_create_without_dispatch_order(order, wanzhanggui_phone):
        text = order_page.create_manual_order_without_dispatch(order)
        main_order_no = order_page.extract_main_order_no(text, order)
        assert main_order_no.startswith("BO"), (
            f"S-FLOW-001 创建不推单主单后未提取到 BO 主单号；"
            f"source_order_no={order.source_order_no}; order_title={order.order_title}; text={text[:1500]}"
        )
        store.mark_order_without_dispatch(
            wanzhanggui_phone=wanzhanggui_phone,
            main_order_no=main_order_no,
            source_order_no=order.source_order_no,
            order_title=order.order_title,
            wanyouji_phones=[],
        )
        bug_reporter.record_if_errors(
            account=wanzhanggui_phone,
            location=f"S-FLOW-001 丸掌柜-订单管理-创建主单不推单：{order.source_order_no}/{order.order_title}",
        )
    else:
        main_order_no = order.main_order_no
        frame = order_page.open_order_management()
        order_page.assert_order_in_pending_accept_status(frame, order)
        if not main_order_no:
            main_order_no = order_page.find_main_order_no_from_order_list(
                source_order_no=order.source_order_no,
                order_title=order.order_title,
            )
        store.mark_order_without_dispatch(
            wanzhanggui_phone=wanzhanggui_phone,
            main_order_no=main_order_no,
            source_order_no=order.source_order_no,
            order_title=order.order_title,
            wanyouji_phones=[],
        )
        bug_reporter.record_if_errors(
            account=wanzhanggui_phone,
            location=f"S-FLOW-001 丸掌柜-订单管理-复用未推单主单：{order.source_order_no}/{order.order_title}",
        )
    detail_status_text = order_page.assert_order_detail_statuses(
        main_order_no=main_order_no,
        source_order_no=order.source_order_no,
        order_title=order.order_title,
        expected_main_status="待接单",
        expected_sub_status="待接单",
    )
    store.mark_task_order_status(
        source_order_no=order.source_order_no,
        status="without_dispatch",
        wanzhanggui_main_status="待接单",
        wanzhanggui_sub_order_status="待接单",
        order_detail_status_text=detail_status_text[:1500],
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-001 丸掌柜订单详情状态校验：{main_order_no or order.source_order_no}",
    )


def resolve_without_dispatch_order(wanzhanggui_phone: str) -> ManualOrderData:
    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()
    explicit_order_title = os.getenv("E2E_S_FLOW_ORDER_TITLE", "").strip()
    if explicit_main_order_no or explicit_source_order_no:
        return ManualOrderData(
            source_order_no=explicit_source_order_no,
            order_title=explicit_order_title or explicit_source_order_no or explicit_main_order_no,
            strategy_name="",
            strategy_type="未推单",
            main_order_no=explicit_main_order_no,
            dispatch_price="0",
        )

    reusable = account_store().find_order_for_flow_case(
        case_id="S-FLOW-003",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanzhanggui_pending_accept_without_sub_order",
    ) or account_store().find_latest_order_without_dispatch(wanzhanggui_phone=wanzhanggui_phone)
    if reusable:
        return ManualOrderData(
            source_order_no=reusable["source_order_no"],
            order_title=reusable.get("order_title", reusable["source_order_no"]),
            strategy_name="",
            strategy_type="未推单",
            main_order_no=reusable.get("main_order_no", ""),
            dispatch_price="0",
        )

    timestamp = datetime.now().strftime("%m%d%H%M%S")
    return ManualOrderData(
        source_order_no=f"E2EORDER{timestamp}",
        order_title=f"E2E手工录单未推单{timestamp}",
        strategy_name="",
        strategy_type="未推单",
        receive_price=manual_order_receive_price(),
        dispatch_price="0",
        role_name=f"SFlow角色{timestamp[-4:]}",
    )


def should_create_without_dispatch_order(order: ManualOrderData, wanzhanggui_phone: str) -> bool:
    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()
    if explicit_main_order_no or explicit_source_order_no:
        return False
    create_mode = os.getenv("E2E_S_FLOW_CREATE_MODE", "reuse").strip().lower()
    if create_mode in {"always", "create"}:
        return True
    return False


def has_reusable_order_identity(order: ManualOrderData) -> bool:
    return bool(order.main_order_no or order.source_order_no or os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "").strip())


def manual_order_receive_price() -> str:
    explicit = os.getenv("E2E_MANUAL_ORDER_RECEIVE_PRICE", "").strip()
    if explicit:
        value = int(explicit)
        assert 50 <= value <= 300, f"E2E_MANUAL_ORDER_RECEIVE_PRICE must be between 50 and 300, got {value}"
        return str(value)
    return str(random.randint(50, 300))
