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_frame(page):
    for frame in page.frames:
        if "test-futong-pc" in frame.url and "/merchantSupplyAuth" in frame.url:
            return frame
    raise AssertionError(f"未找到 merchantSupplyAuth 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}; })()
            })),
            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'][:3000]}")
    print("[inputs]", state["inputs"])
    print("[buttons]", state["buttons"])
    print("[selects]", state["selects"])
    print("[options]", state["options"])


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_frame(page)
        dump_frame(frame, "merchant_supply_auth_before_add")

        clicked = frame.evaluate(
            """() => {
                const buttons = Array.from(document.querySelectorAll('button'));
                const target = buttons.find(el => {
                    const text = (el.innerText || el.textContent || '').trim();
                    return text.includes('新增') || text.includes('新 增');
                });
                if (!target) return false;
                target.click();
                return true;
            }"""
        )
        if not clicked:
            raise AssertionError("未在工作室授权 iframe 中点击到新 增按钮")
        page.wait_for_timeout(2000)
        dump_frame(frame, "merchant_supply_auth_after_add")

        first_select = frame.locator(".ant-modal .ant-select-selector").first
        if first_select.count():
            first_select.click()
            page.wait_for_timeout(1000)
            dump_frame(frame, "merchant_supply_auth_supply_options")
            frame.locator(".ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option-content").filter(
                has_text="丸友集"
            ).first.click()
            page.wait_for_timeout(1500)
            dump_frame(frame, "merchant_supply_auth_after_select_wanyouji")

            selectors = frame.locator(".ant-modal .ant-select-selector")
            if selectors.count() > 1:
                selectors.nth(1).click()
                page.wait_for_timeout(1000)
                dump_frame(frame, "merchant_supply_auth_workshop_options")
        browser.close()


if __name__ == "__main__":
    main()
