from __future__ import annotations

import os
from dataclasses import dataclass
from datetime import datetime

import pytest
from playwright.sync_api import Page

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


@dataclass(frozen=True)
class AutoAcceptanceConfigCase:
    case_id: str
    wanzhanggui_phone: str
    wanyouji_phone: str
    merchant_name: str
    workshop_name: str
    strategy_name: str
    strategy_type: str
    game_name: str
    game_region: str
    game_server: str
    service_project: str
    max_private_order_count: str


def first_config_case(settings) -> AutoAcceptanceConfigCase:
    return AutoAcceptanceConfigCase(
        case_id="AUTO-ACCEPT-CONFIG-001",
        wanzhanggui_phone=os.getenv("E2E_AUTO_ACCEPT_CONFIG_WANZHANGGUI_PHONE", "17788888888").strip(),
        wanyouji_phone=os.getenv("E2E_AUTO_ACCEPT_CONFIG_WANYOUJI_PHONE", "18800000001").strip(),
        merchant_name=os.getenv("E2E_AUTO_ACCEPT_CONFIG_MERCHANT", "测试001").strip(),
        workshop_name=os.getenv("E2E_AUTO_ACCEPT_CONFIG_WORKSHOP", "旺仔工作室").strip(),
        strategy_name=os.getenv("E2E_AUTO_ACCEPT_CONFIG_STRATEGY", "指定-旺仔").strip(),
        strategy_type=os.getenv("E2E_AUTO_ACCEPT_CONFIG_STRATEGY_TYPE", "单平台指定").strip(),
        game_name=os.getenv("E2E_AUTO_ACCEPT_CONFIG_GAME", "王者").strip(),
        game_region=os.getenv("E2E_AUTO_ACCEPT_CONFIG_GAME_REGION", "WeGame").strip(),
        game_server=os.getenv("E2E_AUTO_ACCEPT_CONFIG_GAME_SERVER", "微信2区-国士无双").strip(),
        service_project=os.getenv("E2E_AUTO_ACCEPT_CONFIG_SERVICE_PROJECT", "排位").strip(),
        max_private_order_count=os.getenv("E2E_AUTO_ACCEPT_CONFIG_MAX_PRIVATE_ORDER_COUNT", "800").strip(),
    )


@pytest.mark.e2e_auto_acceptance
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_auto_acceptance_config_001_private_order_rules_positive(
    page: Page,
    settings,
    bug_reporter,
    dual_account_pages,
) -> None:
    case = first_config_case(settings)
    store = account_store()
    wanzhanggui_account = store.find(phone=case.wanzhanggui_phone)
    wanyouji_account = store.find(phone=case.wanyouji_phone)
    assert wanzhanggui_account is not None, f"台账中未找到丸掌柜账号：{case.wanzhanggui_phone}"
    assert wanyouji_account is not None, f"台账中未找到丸友集账号：{case.wanyouji_phone}"
    assert wanzhanggui_account.wanzhanggui_status == "opened", (
        f"丸掌柜账号未开通；phone={case.wanzhanggui_phone}; status={wanzhanggui_account.wanzhanggui_status}"
    )
    assert wanyouji_account.wanyouji_status == "opened", (
        f"丸友集账号未开通；phone={case.wanyouji_phone}; status={wanyouji_account.wanyouji_status}"
    )

    wanzhanggui_page, wanyouji_page = dual_account_pages.pair(case.wanzhanggui_phone, case.wanyouji_phone)
    order_page = WanzhangguiOrderPage(wanzhanggui_page, settings.tenant_home_url, bug_reporter)
    fulfillment_page = WanyoujiFulfillmentPage(wanyouji_page, settings.tenant_home_url, bug_reporter)

    order_page.login_main_account(case.wanzhanggui_phone, wanzhanggui_account.password)
    order_page.ensure_workshop_guarantee(case.workshop_name, enabled=False)
    bug_reporter.record_if_errors(
        account=case.wanzhanggui_phone,
        location=f"{case.case_id} 发单前关闭工作室担保 {case.workshop_name}",
    )

    fulfillment_page.login_main_account(case.wanyouji_phone, wanyouji_account.password)
    fulfillment_page.ensure_auto_acceptance_private_order_rules(
        merchant_name=case.merchant_name,
        game_name=case.game_name,
        service_project=case.service_project,
        max_private_order_count=case.max_private_order_count,
    )
    bug_reporter.record_if_errors(
        account=case.wanyouji_phone,
        location=(
            f"{case.case_id} 通过编辑画像配置智能接单：商家开关开启，游戏+服务项目同组合命中，"
            f"每日私单最大接单量={case.max_private_order_count}"
        ),
    )

    timestamp = datetime.now().strftime("%m%d%H%M%S")
    source_order_no = (
        os.getenv("E2E_AUTO_ACCEPT_CONFIG_SOURCE_ORDER_NO", "").strip()
        or f"AACFG{timestamp}"
    )
    order_title = (
        os.getenv("E2E_AUTO_ACCEPT_CONFIG_ORDER_TITLE", "").strip()
        or f"E2E智能接单配置{timestamp}"
    )
    order = ManualOrderData(
        source_order_no=source_order_no,
        order_title=order_title,
        sub_order_title=f"{order_title}私单配置准入",
        strategy_name=case.strategy_name,
        strategy_type=case.strategy_type,
        game_name=case.game_name,
        game_region=case.game_region,
        game_server=case.game_server,
        service_project=case.service_project,
        role_name=f"AACFG角色{timestamp[-4:]}",
    )

    order_page.login_main_account(case.wanzhanggui_phone, wanzhanggui_account.password)
    order_page.create_manual_order(order)
    bug_reporter.record_if_errors(
        account=case.wanzhanggui_phone,
        location=(
            f"{case.case_id} 丸掌柜创建匹配游戏+服务项目的私单并推送目标工作室："
            f"{source_order_no}/{order_title}"
        ),
    )

    row_text = order_page.refresh_order_list_and_get_row_text(source_order_no, order_title)
    assert "代练中" in row_text, (
        "满足商家自动接指派单开启、游戏+服务项目同组合命中、最大接单量800后，"
        f"丸掌柜订单未自动进入代练中；source_order_no={source_order_no}; row_text={row_text[:1500]}"
    )

    fulfillment_page.login_main_account(case.wanyouji_phone, wanyouji_account.password)
    accepted_row_text = fulfillment_page.verify_workshop_order_list_status(
        source_order_no,
        order_title,
        ["已接单", "接单"],
    )
    bug_reporter.record_if_errors(
        account=case.wanyouji_phone,
        location=f"{case.case_id} 丸友集订单列表校验自动接单成功：{source_order_no}/{order_title}",
    )

    store.mark_order_dispatched(
        wanzhanggui_phone=case.wanzhanggui_phone,
        source_order_no=source_order_no,
        order_title=order_title,
        strategy_name=case.strategy_name,
        strategy_type=case.strategy_type,
        wanyouji_phones=[case.wanyouji_phone],
    )
    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="task_accepted",
        task_accept_scope="已接单",
        task_wanyouji_phone=case.wanyouji_phone,
    )
    assert source_order_no in accepted_row_text or order_title in accepted_row_text
