from __future__ import annotations

import os
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()
    phones = [item.strip() for item in os.getenv("E2E_MEMBER_APPROVE_PHONES", "").split(",") if item.strip()]
    if not phones:
        raise SystemExit("请设置 E2E_MEMBER_APPROVE_PHONES，例如：19154060742,19043612410")

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

    known_names = {
        "19154060742": "E2E打手2949",
        "19043612410": "E2E打手2444",
    }

    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 phone in phones:
            account = store.find(phone=phone)
            member = WanyoujiMemberData(
                phone=phone,
                password=account.password if account else "test123456",
                role=account.member_role if account and account.member_role else "打手",
                name=account.contact_name if account and account.contact_name else known_names.get(phone, ""),
                product="丸友集",
            )
            print(f"审批子成员：{member.phone} {member.role} {member.name}")
            member_page.confirm_registered_member_from_main_account(member)
            store.mark_wanyouji_member_created(
                parent=parent,
                phone=member.phone,
                password=member.password,
                role=member.role,
                contact_name=member.name or f"E2E{member.role}{member.phone[-4:]}",
                status="approved",
            )
        context.close()
        browser.close()

    print(f"已处理指定子成员 {len(phones)} 个。")


if __name__ == "__main__":
    main()
