from __future__ import annotations

import os
from datetime import datetime

import pytest
from playwright.sync_api import Page

from e2e.pages.wanyouji_member_page import InvitationSmsPending, WanyoujiMemberData, WanyoujiMemberPage
from e2e.utils.account_store import account_store
from e2e.utils.data_factory import random_mainland_phone
from e2e.utils.verification_code import FeishuConfig, VerificationCodeProvider


@pytest.mark.e2e_member_001
@pytest.mark.e2e_member_002
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_丸友集企业新增客服或打手子成员并写入台账(page: Page, settings, bug_reporter) -> None:
    role_mode = os.getenv("E2E_MEMBER_ROLE", "全部").strip()
    assert role_mode in {"全部", "客服", "打手"}, (
        "E2E_MEMBER_ROLE 仅支持：全部、客服、打手；"
        f"当前值：{role_mode}"
    )

    roles = ["客服", "打手"] if role_mode == "全部" else [role_mode]
    product = os.getenv("E2E_MEMBER_PRODUCT", "丸友集").strip()
    password = os.getenv("E2E_MEMBER_PASSWORD", settings.register_password)
    phone_prefix = os.getenv("E2E_MEMBER_PHONE_PREFIX", settings.phone_prefix)
    parent_phone = os.getenv("E2E_MEMBER_PARENT_PHONE", "").strip()

    store = account_store()
    parent = store.find(phone=parent_phone) if parent_phone else store.find_wanyouji_owner_for_member()
    if parent is None:
        pytest.skip("台账中没有已开通丸友集产品的主账号，请先执行注册/认证/开通丸友集流程，或检查 E2E_MEMBER_PARENT_PHONE。")
    assert parent.certification_status == "approved" and parent.wanyouji_status == "opened", (
        f"指定主账号未处于已认证且已开通丸友集状态：{parent.phone}；"
        f"certification_status={parent.certification_status}; wanyouji_status={parent.wanyouji_status}"
    )

    code_provider = VerificationCodeProvider(
        mode=settings.verification_code_mode,
        static_code=settings.verification_code_static,
        manual_code_file=settings.manual_code_file,
        manual_timeout_seconds=settings.manual_code_timeout_seconds,
        manual_poll_interval_seconds=settings.manual_code_poll_interval_seconds,
        feishu_config=FeishuConfig(
            app_id=settings.feishu_app_id,
            app_secret=settings.feishu_app_secret,
            chat_id=settings.feishu_chat_id,
            timeout_seconds=settings.feishu_timeout_seconds,
            poll_interval_seconds=settings.feishu_poll_interval_seconds,
        ),
    )
    member_page = WanyoujiMemberPage(
        page,
        settings.tenant_home_url,
        bug_reporter,
        code_provider=code_provider,
    )
    member_page.login_main_account(parent.phone, parent.password)
    bug_reporter.record_if_errors(account=parent.phone, location="丸友集主账号登录")

    for role in roles:
        member = build_member(role=role, product=product, password=password, phone_prefix=phone_prefix)
        try:
            selected_role, registered = member_page.invite_member(member)
            status = "registered" if registered else "invitation_created"
            invite_url = ""
        except InvitationSmsPending as exc:
            selected_role = role
            status = "sms_pending"
            invite_url = exc.invite_url
        bug_reporter.record_if_errors(
            account=parent.phone,
            location=f"丸友集-企业管理-成员管理-新增{role}子成员：{member.phone}",
        )
        store.mark_wanyouji_member_created(
            parent=parent,
            phone=member.phone,
            password=member.password,
            role=selected_role or member.role,
            contact_name=member.name,
            status=status,
            invite_url=invite_url,
        )


def build_member(role: str, product: str, password: str, phone_prefix: str) -> WanyoujiMemberData:
    timestamp = datetime.now().strftime("%m%d%H%M%S")
    suffix = timestamp[-4:]
    return WanyoujiMemberData(
        phone=random_mainland_phone(phone_prefix),
        password=password,
        role=role,
        name=f"E2E{role}{suffix}",
        product=product,
    )
