from __future__ import annotations

import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from e2e.pages.wanyouji_member_page import WanyoujiMemberData, WanyoujiMemberPage
from e2e.utils.account_store import account_store


def main() -> None:
    load_dotenv()
    store = account_store()
    parent = store.find_wanyouji_owner_for_member()
    if parent is None:
        raise SystemExit("台账中没有已开通丸友集产品的主账号")

    pending = [
        account
        for account in store.load()
        if account.account_type == "sub"
        and account.member_role in {"客服", "打手"}
        and account.member_status not in {"approved", "registered"}
    ]
    if not pending:
        print("台账中没有待审批的客服/打手子成员。")
        return

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        member_page = WanyoujiMemberPage(page, "https://test-lianlianyun.lianlianwz.com/home")
        member_page.login_main_account(parent.phone, parent.password)
        for account in pending:
            member = WanyoujiMemberData(
                phone=account.phone,
                password=account.password,
                role=account.member_role,
                name=account.contact_name,
                product="丸友集",
            )
            print(f"审批子成员：{member.phone} {member.role} {member.name}")
            try:
                member_page.confirm_registered_member_from_main_account(member)
            except AssertionError as exc:
                reason = str(exc).encode("gbk", errors="ignore").decode("gbk", errors="ignore")[:300]
                print(f"跳过：{member.phone} 暂未在丸友集成员列表出现，可能还未完成邀请注册。原因：{reason}")
                continue
            store.mark_wanyouji_member_created(
                parent=parent,
                phone=member.phone,
                password=member.password,
                role=member.role,
                contact_name=member.name,
                status="approved",
                invite_url=account.member_invite_url,
            )
        context.close()
        browser.close()

    print(f"已处理待审批子成员 {len(pending)} 个。")


if __name__ == "__main__":
    main()
