from __future__ import annotations

import json
import sys
from pathlib import Path

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.utils.account_store import account_store


OUT_DIR = Path("runtime/member_probe/mobile_invite_form")


def main() -> None:
    store = account_store()
    account = next(
        (
            item
            for item in reversed(store.load())
            if item.account_type == "sub" and item.member_invite_url
        ),
        None,
    )
    if account is None:
        raise SystemExit("台账中没有带邀请链接的子账号")

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True)
        context = browser.new_context(
            viewport={"width": 390, "height": 844},
            screen={"width": 390, "height": 844},
            is_mobile=True,
            has_touch=True,
            device_scale_factor=2,
            user_agent=(
                "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) "
                "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
            ),
        )
        page = context.new_page()
        page.goto(account.member_invite_url, wait_until="domcontentloaded")
        for _ in range(15):
            text = page.locator("body").inner_text(timeout=1000)
            if "加载中" not in text and ("获取验证码" in text or "登录" in text or "立即加入" in text):
                break
            page.wait_for_timeout(1000)
        payload = {
            "account": account.phone,
            "invite_url": account.member_invite_url,
            "url": page.url,
            "text": page.locator("body").inner_text(timeout=5000),
            "nodes": page.evaluate(
                """() => Array.from(document.querySelectorAll('input, textarea, taro-input-core, button, taro-button-core, taro-view-core, img'))
                  .map((el, index) => {
                    const nativeInput = el.matches('input, textarea') ? el : el.querySelector('input, textarea');
                    const target = nativeInput || el;
                    const r = target.getBoundingClientRect();
                    return {
                      index,
                      tag: el.tagName,
                      targetTag: target.tagName,
                      text: (el.innerText || el.textContent || '').trim(),
                      placeholder: target.getAttribute?.('placeholder') || el.getAttribute?.('placeholder') || '',
                      type: target.getAttribute?.('type') || '',
                      value: target.value || '',
                      src: el.getAttribute?.('src') || '',
                      className: String(el.className || ''),
                      rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                    };
                  })
                  .filter(item => item.rect.width > 0 && item.rect.height > 0 || item.text || item.placeholder || item.src)
                  .slice(0, 300)"""
            ),
        }
        (OUT_DIR / "invite_form.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=OUT_DIR / "invite_form.png", full_page=True)
        context.close()
        browser.close()

    print(f"已保存移动端邀请页表单探测：{OUT_DIR.resolve()}")


if __name__ == "__main__":
    main()
