from __future__ import annotations

import os
from datetime import datetime

from playwright.sync_api import Page

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


def ensure_wanyouji_customer_service_member(
    *,
    page: Page,
    settings,
    bug_reporter,
    parent: E2EAccount,
) -> E2EAccount:
    store = account_store()
    existing = store.find_wanyouji_customer_service_member(parent.phone)
    if existing is not None:
        return existing

    member = WanyoujiMemberData(
        phone=random_mainland_phone(os.getenv("E2E_MEMBER_PHONE_PREFIX", settings.phone_prefix)),
        password=os.getenv("E2E_MEMBER_PASSWORD", settings.register_password),
        role="客服",
        name=f"E2E客服{datetime.now():%H%M%S}",
        product=os.getenv("E2E_MEMBER_PRODUCT", "丸友集"),
    )
    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)
    try:
        selected_role, registered = member_page.invite_member(member)
        status = "registered" if registered else "invitation_created"
        invite_url = ""
    except InvitationSmsPending as exc:
        selected_role = "客服"
        status = "sms_pending"
        invite_url = exc.invite_url
    bug_reporter.record_if_errors(
        account=parent.phone,
        location=f"S-FLOW 丸友集售后客服前置创建：{member.phone}",
    )
    created = 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,
    )
    assert created.member_status in {"registered", "approved"}, (
        f"丸友集售后客服成员未完成注册/审核，无法在售后客服下拉中选择；"
        f"phone={created.phone}; status={created.member_status}; invite_url={created.member_invite_url}"
    )
    return created


def ensure_wanyouji_player_member(
    *,
    page: Page,
    settings,
    bug_reporter,
    parent: E2EAccount,
) -> E2EAccount:
    store = account_store()
    for account in reversed(store.load()):
        if (
            account.account_type == "sub"
            and account.parent_phone == parent.phone
            and account.member_role == "打手"
            and account.member_status in {"registered", "approved"}
            and account.wanyouji_status == "opened"
        ):
            return account

    member = WanyoujiMemberData(
        phone=random_mainland_phone(os.getenv("E2E_MEMBER_PHONE_PREFIX", settings.phone_prefix)),
        password=os.getenv("E2E_MEMBER_PASSWORD", settings.register_password),
        role="打手",
        name=f"E2E打手{datetime.now():%H%M%S}",
        product=os.getenv("E2E_MEMBER_PRODUCT", "丸友集"),
    )
    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)
    try:
        selected_role, registered = member_page.invite_member(member)
        status = "registered" if registered else "invitation_created"
        invite_url = ""
    except InvitationSmsPending as exc:
        selected_role = "打手"
        status = "sms_pending"
        invite_url = exc.invite_url
    bug_reporter.record_if_errors(
        account=parent.phone,
        location=f"S-FLOW 丸友集打手账号前置创建：{member.phone}",
    )
    created = 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,
    )
    assert created.member_status in {"registered", "approved"}, (
        "丸友集打手成员未完成注册/审核，无法继续打手接单；"
        f"phone={created.phone}; status={created.member_status}; invite_url={created.member_invite_url}"
    )
    return created
