from __future__ import annotations

import sys
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from playwright.sync_api import sync_playwright

from e2e.pages.wanzhanggui_push_page import WanzhangguiPushPage


租户首页 = "https://test-lianlianyun.lianlianwz.com/home"
丸掌柜账号 = "19147509308"
丸掌柜密码 = "test123456"
输出目录 = Path("runtime/probes/wanzhanggui_dispatch_manual_select")


def 保存现场(page, frame, name: str) -> None:
    输出目录.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    page.screenshot(path=输出目录 / f"{timestamp}-{name}.png", full_page=True)
    payload = frame.evaluate(
        """() => {
            const modal = Array.from(document.querySelectorAll('.ant-modal'))
              .filter(el => {
                const r = el.getBoundingClientRect();
                return r.width > 0 && r.height > 0;
              }).pop();
            const selectors = Array.from(document.querySelectorAll('.ant-modal .ant-select-selector'))
              .map((el, index) => ({
                index,
                text: (el.innerText || el.textContent || '').trim(),
                html: el.outerHTML,
                rect: (() => {
                  const r = el.getBoundingClientRect();
                  return { x: r.x, y: r.y, width: r.width, height: r.height };
                })(),
              }));
            const dropdowns = Array.from(document.querySelectorAll('.ant-select-dropdown'))
              .map((el, index) => ({
                index,
                hidden: String(el.className || '').includes('ant-select-dropdown-hidden'),
                text: (el.innerText || el.textContent || '').trim(),
                html: el.outerHTML,
              }));
            return {
              url: location.href,
              bodyText: document.body.innerText,
              modalText: modal ? (modal.innerText || modal.textContent || '').trim() : '',
              selectors,
              dropdowns,
            };
        }"""
    )
    (输出目录 / f"{timestamp}-{name}.txt").write_text(str(payload), encoding="utf-8")


def 已选择工作室(frame) -> list[str]:
    return list(
        frame.evaluate(
            """() => {
                const selectors = Array.from(document.querySelectorAll('.ant-modal .ant-select-selector'));
                const selector = selectors[1];
                if (!selector) return [];
                return Array.from(selector.querySelectorAll('.ant-select-selection-item, .ant-select-selection-overflow-item'))
                  .map(el => (el.innerText || el.textContent || '').trim())
                  .filter(Boolean)
                  .filter(text => text !== '+ 0 ...' && !/^\\+\\s*\\d+/.test(text));
            }"""
        )
    )


def main() -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        push_page = WanzhangguiPushPage(page, 租户首页)

        push_page.login_main_account(丸掌柜账号, 丸掌柜密码)
        frame = push_page.open_dispatch_strategy()
        strategy_name = f"E2E探测策略{datetime.now().strftime('%m%d%H%M%S')}"

        push_page.click_frame_button_by_js(frame, "新增策略")
        page.wait_for_timeout(1200)
        name_input = frame.locator(".ant-modal input[placeholder='例如: 默认推单策略']").first
        name_input.fill(strategy_name)
        push_page.click_modal_radio(frame, "多工作室同时分发")
        push_page.select_modal_option(frame, 0, "丸友集")
        page.wait_for_timeout(1200)

        selectors = frame.locator(".ant-modal .ant-select-selector")
        selectors.nth(1).click(force=True)
        page.wait_for_timeout(800)
        保存现场(page, frame, "opened-dropdown-before-manual")

        print("")
        print("[probe] 已打开“授权商户号”下拉框。")
        print("[probe] 请你在浏览器里只打开这一次下拉框，顺位勾选第 1 行和第 2 行，然后点击弹窗空白处。")
        print("[probe] 我会记录选中后的 DOM、截图和已选标签，用来修正自动化脚本。")

        last_selected: list[str] = []
        for _ in range(240):
            current = 已选择工作室(frame)
            if current and current != last_selected:
                last_selected = current
                print(f"[probe] 当前已选：{current}")
            if len(current) >= 2:
                page.wait_for_timeout(1500)
                保存现场(page, frame, "after-manual-select")
                print(f"[probe] 已保存手动选择现场：{输出目录}")
                page.wait_for_timeout(5000)
                context.close()
                browser.close()
                return
            page.wait_for_timeout(500)

        保存现场(page, frame, "manual-select-timeout")
        print(f"[probe] 等待超时，已保存现场：{输出目录}")
        page.wait_for_timeout(5000)
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
