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
from e2e.utils.verification_code import FeishuConfig, VerificationCodeProvider


def main() -> None:
    load_dotenv()
    phone = os.getenv("E2E_MEMBER_DEBUG_PHONE", "").strip()
    role = os.getenv("E2E_MEMBER_DEBUG_ROLE", "打手").strip()
    name = os.getenv("E2E_MEMBER_DEBUG_NAME", f"DEBUG{role}").strip()
    if not phone:
        raise SystemExit("请设置 E2E_MEMBER_DEBUG_PHONE")
    store = account_store()
    parent = store.find_wanyouji_owner_for_member()
    if parent is None:
        raise SystemExit("台账中没有丸友集主账号")
    provider = VerificationCodeProvider(
        mode=os.getenv("E2E_VERIFICATION_CODE_MODE", "feishu"),
        static_code=os.getenv("E2E_VERIFICATION_CODE_STATIC", ""),
        manual_code_file=os.getenv("E2E_MANUAL_CODE_FILE", "runtime/sms_code.txt"),
        manual_timeout_seconds=int(os.getenv("E2E_MANUAL_CODE_TIMEOUT_SECONDS", "180")),
        manual_poll_interval_seconds=int(os.getenv("E2E_MANUAL_CODE_POLL_INTERVAL_SECONDS", "2")),
        feishu_config=FeishuConfig(
            app_id=os.getenv("FEISHU_APP_ID", ""),
            app_secret=os.getenv("FEISHU_APP_SECRET", ""),
            chat_id=os.getenv("FEISHU_CHAT_ID", ""),
            timeout_seconds=int(os.getenv("FEISHU_TIMEOUT_SECONDS", "60")),
            poll_interval_seconds=int(os.getenv("FEISHU_POLL_INTERVAL_SECONDS", "3")),
        ),
    )
    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",
            code_provider=provider,
        )
        member = WanyoujiMemberData(phone=phone, password="test123456", role=role, name=name)
        member_page.login_main_account(parent.phone, parent.password)
        member_page.confirm_registered_member_from_main_account(member)
        member_page.verify_member_can_login_by_sms(member)
        print(page.locator("body").inner_text(timeout=5000)[:2000])
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
