from __future__ import annotations

import json
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 WanyoujiMemberPage
from e2e.utils.account_store import account_store


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


def main() -> None:
    load_dotenv()
    phone = os.getenv("E2E_MEMBER_DEBUG_PHONE", "").strip()
    store = account_store()
    parent = store.find_wanyouji_owner_for_member()
    if parent is None:
        raise SystemExit("台账中没有丸友集主账号")
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    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)
        frame = member_page.open_member_management()
        dump(page, frame, "01_成员管理")
        member_page.click_member_management_tab(frame, ["邀请管理"])
        dump(page, frame, "02_邀请管理")
        if phone:
            member_page.search_if_possible(frame, phone)
            dump(page, frame, "03_邀请管理搜索手机号")
        context.close()
        browser.close()


def dump(page, frame, name: str) -> None:
    payload = {
        "url": page.url,
        "frame_url": frame.url,
        "text": frame.locator("body").inner_text(timeout=5000)[:5000],
        "buttons": member_buttons(frame),
        "nodes": nodes(frame),
    }
    (OUT_DIR / f"{name}.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    page.screenshot(path=OUT_DIR / f"{name}.png", full_page=True)


def member_buttons(frame) -> list[str]:
    return list(frame.evaluate("() => Array.from(document.querySelectorAll('button, a')).map(el => (el.innerText || el.textContent || '').trim()).filter(Boolean)"))


def nodes(frame) -> list[dict]:
    return list(
        frame.evaluate(
            """() => Array.from(document.querySelectorAll('button, a, span, div, input, .ant-select-selector'))
              .map((el, index) => {
                const r = el.getBoundingClientRect();
                return {
                  index,
                  tag: el.tagName,
                  text: (el.innerText || el.textContent || '').trim(),
                  placeholder: el.getAttribute?.('placeholder') || '',
                  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))
              .slice(0, 800)"""
        )
    )


if __name__ == "__main__":
    main()
