from __future__ import annotations

import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from e2e.pages.tenant_auth_page import TenantAuthPage


load_dotenv()
sys.stdout.reconfigure(encoding="utf-8")

WZG_CONSOLE_URL = "https://test-merchant-lianlianyun.lianlianwz.com/productConsole?productCode=P20251204180120231330"
OUT_DIR = Path("runtime/push_probe")


def click_sidebar_text(page, text: str, nth: int = 0, right_edge: bool = False) -> None:
    boxes = page.evaluate(
        """text => Array.from(document.querySelectorAll('taro-view-core, div, span'))
            .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect() }))
            .filter(item => item.r.x >= 0 && item.r.x < 240 && item.r.y > 40)
            .filter(item => item.r.width > 20 && item.r.width < 240 && item.r.height > 10)
            .filter(item => item.text === text || item.text.split(/\\s+/).includes(text))
            .sort((a, b) => {
                if (a.text === text && b.text !== text) return -1;
                if (b.text === text && a.text !== text) return 1;
                return a.r.y - b.r.y || (a.r.width * a.r.height) - (b.r.width * b.r.height);
            })
            .map(item => ({ x: item.r.x, y: item.r.y, width: item.r.width, height: item.r.height, text: item.text }))""",
        text,
    )
    if len(boxes) <= nth:
        raise AssertionError(f"未找到菜单 {text}，候选：{boxes}")
    box = boxes[nth]
    x = box["x"] + box["width"] - 16 if right_edge else box["x"] + box["width"] / 2
    page.mouse.click(x, box["y"] + box["height"] / 2)
    page.wait_for_load_state("domcontentloaded")
    page.wait_for_timeout(1500)


def futong_dispatch_frame(page):
    for frame in page.frames:
        if "test-futong-pc" in frame.url and "/dispatchStrategy" in frame.url:
            return frame
    raise AssertionError(f"未找到 dispatchStrategy iframe：{[frame.url for frame in page.frames]}")


def dump_frame(frame, name: str) -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    state = frame.evaluate(
        """() => ({
            url: location.href,
            text: document.body.innerText,
            inputs: Array.from(document.querySelectorAll('input, textarea')).map(el => ({
                placeholder: el.getAttribute('placeholder') || '',
                value: el.value || '',
                type: el.getAttribute('type') || '',
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
            })),
            buttons: Array.from(document.querySelectorAll('button')).map(el => ({
                text: (el.innerText || el.textContent || '').trim(),
                disabled: el.disabled,
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
            })),
            selects: Array.from(document.querySelectorAll('.ant-select-selector')).map(el => ({
                text: (el.innerText || el.textContent || '').trim(),
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
            })),
            radios: Array.from(document.querySelectorAll('label, .ant-radio-wrapper')).map(el => ({
                text: (el.innerText || el.textContent || '').trim(),
                cls: String(el.className || ''),
                rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
            })),
            options: Array.from(document.querySelectorAll('.ant-select-item-option-content')).map(el => (el.innerText || el.textContent || '').trim())
        })"""
    )
    (OUT_DIR / f"{name}.txt").write_text(str(state), encoding="utf-8")
    print(f"[{name}]\n{state['text'][:4000]}")
    print("[inputs]", state["inputs"])
    print("[buttons]", state["buttons"])
    print("[selects]", state["selects"])
    print("[radios]", state["radios"])
    print("[options]", state["options"])


def click_button_by_text(frame, text: str) -> None:
    clicked = frame.evaluate(
        """text => {
            const buttons = Array.from(document.querySelectorAll('button'));
            const normalized = text.replace(/\\s+/g, '');
            const target = buttons.find(el => {
                const value = (el.innerText || el.textContent || '').trim();
                return value === text || value.replace(/\\s+/g, '').includes(normalized);
            });
            if (!target) return false;
            target.click();
            return true;
        }""",
        text,
    )
    if not clicked:
        raise AssertionError(f"未点击到按钮 {text}")


def main() -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        auth_page = TenantAuthPage(page, os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home"))
        auth_page.login_main_account(
            os.getenv("E2E_PROBE_WZG_PHONE", "19147509308"),
            os.getenv("E2E_PROBE_WZG_PASSWORD", "test123456"),
        )
        page.goto(WZG_CONSOLE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(3000)
        click_sidebar_text(page, "履约工作室/平台", right_edge=True)
        click_sidebar_text(page, "工作室管理")
        click_sidebar_text(page, "推单配置")
        frame = futong_dispatch_frame(page)
        dump_frame(frame, "dispatch_strategy_before_add")
        click_button_by_text(frame, "新增策略")
        page.wait_for_timeout(2000)
        dump_frame(frame, "dispatch_strategy_after_add")
        for index in range(frame.locator(".ant-modal .ant-select-selector").count()):
            frame.locator(".ant-modal .ant-select-selector").nth(index).click()
            page.wait_for_timeout(800)
            dump_frame(frame, f"dispatch_strategy_select_{index}_options")
            if index == 0:
                option = frame.locator(
                    ".ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option-content"
                ).filter(has_text="丸友集").first
                option.click()
                page.wait_for_timeout(1500)
                dump_frame(frame, "dispatch_strategy_after_select_wanyouji")
        browser.close()


if __name__ == "__main__":
    main()
