from __future__ import annotations

import json
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/enterprise_member_invite_modal")


def main() -> None:
    load_dotenv()
    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=150)
        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()
        member_page.open_add_member_modal(frame)
        page.wait_for_timeout(2000)
        dump(page, frame, "01_邀请员工弹窗")
        click_first_select(frame)
        page.wait_for_timeout(1500)
        dump(page, frame, "02_点击第一个下拉后")
        context.close()
        browser.close()


def click_first_select(frame) -> None:
    frame.evaluate(
        """() => {
            const nodes = Array.from(document.querySelectorAll('*'))
              .map(el => ({ el, text: (el.innerText || el.textContent || '').trim(), cls: String(el.className || ''), r: el.getBoundingClientRect() }))
              .filter(item => item.r.width > 0 && item.r.height > 0)
              .filter(item => item.cls.includes('select') || item.text.includes('请先选择产品'));
            nodes.sort((a, b) => a.r.y - b.r.y || a.r.x - b.r.x);
            const target = nodes[0]?.el;
            if (target) target.click();
        }"""
    )


def dump(page, frame, name: str) -> None:
    payload = {
        "page_url": page.url,
        "frame_url": frame.url,
        "page_text": safe_page_text(page)[:3000],
        "frame_text": safe_frame_text(frame)[:4000],
        "frame_nodes": safe_nodes(frame),
    }
    (OUT_DIR / f"{name}.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    try:
        page.screenshot(path=OUT_DIR / f"{name}.png", full_page=True)
    except Exception:
        pass


def safe_page_text(page) -> str:
    try:
        return page.locator("body").inner_text(timeout=5000)
    except Exception as exc:
        return f"<无法读取页面文本：{exc}>"


def safe_frame_text(frame) -> str:
    try:
        return frame.locator("body").inner_text(timeout=5000)
    except Exception as exc:
        return f"<无法读取 frame 文本：{exc}>"


def safe_nodes(frame) -> list[dict]:
    return list(
        frame.evaluate(
            """() => Array.from(document.querySelectorAll('*'))
              .map((el, index) => {
                const r = el.getBoundingClientRect();
                return {
                  index,
                  tag: el.tagName,
                  text: (el.innerText || el.textContent || '').trim(),
                  placeholder: el.getAttribute?.('placeholder') || '',
                  role: el.getAttribute?.('role') || '',
                  aria: el.getAttribute?.('aria-label') || '',
                  className: String(el.className || ''),
                  id: el.id || '',
                  rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                };
              })
              .filter(item => item.rect.width > 0 && item.rect.height > 0)
              .filter(item => item.text || item.placeholder || item.role || item.aria || item.className.includes('select'))
              .slice(0, 1200)"""
        )
    )


if __name__ == "__main__":
    main()
