from __future__ import annotations

from pathlib import Path

from playwright.sync_api import sync_playwright


def main() -> None:
    reports = Path("reports")
    reports.mkdir(exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto("https://test-lianlianyun.lianlianwz.com/login", wait_until="domcontentloaded")
        page.wait_for_timeout(1200)
        page.locator("#password_login_phone").fill("19361091624")
        page.locator("#password_login_password").fill("test123456")
        page.get_by_text("登 录", exact=True).click()
        page.wait_for_timeout(2500)
        page.evaluate(
            """() => {
                const candidates = Array.from(document.querySelectorAll('taro-view-core, div'))
                    .filter(el => (el.innerText || el.textContent || '').includes('主账号'));
                candidates.sort((a, b) => {
                    const ar = a.getBoundingClientRect();
                    const br = b.getBoundingClientRect();
                    return (ar.width * ar.height) - (br.width * br.height);
                });
                const target = candidates.find(el => {
                    const r = el.getBoundingClientRect();
                    return r.width > 80 && r.height > 30;
                });
                if (target) target.click();
            }"""
        )
        page.wait_for_timeout(2500)
        print("HOME", page.url)
        print("TITLE", page.title())
        print(page.locator("body").inner_text(timeout=10000))

        page.evaluate(
            """() => {
                const target = Array.from(document.querySelectorAll('span,div,taro-view-core'))
                    .find(el => {
                        const text = (el.innerText || el.textContent || '').trim();
                        const r = el.getBoundingClientRect();
                        return text === '订阅购买' && r.width > 0 && r.height > 0;
                    });
                if (!target) throw new Error('未找到可见的订阅购买入口');
                target.click();
            }"""
        )
        page.wait_for_load_state("domcontentloaded")
        page.wait_for_timeout(3000)
        print("SUBSCRIBE_URL", page.url)
        print(page.locator("body").inner_text(timeout=10000)[:8000])
        print("VISIBLE_ELEMENTS")
        elements = page.evaluate(
            """() => Array.from(document.querySelectorAll('input,textarea,button,taro-button-core,taro-view-core,a,.ant-menu-item,.ant-menu-submenu-title,.ant-card,.ant-table-row,.ant-select-selector,[class*=menu],[class*=nav]'))
                .map((e, i) => {
                    const r = e.getBoundingClientRect();
                    return {
                        i,
                        tag: e.tagName,
                        id: e.id,
                        href: e.getAttribute('href'),
                        type: e.getAttribute('type'),
                        placeholder: e.getAttribute('placeholder'),
                        text: (e.innerText || e.textContent || '').trim(),
                        cls: String(e.className),
                        x: Math.round(r.x),
                        y: Math.round(r.y),
                        w: Math.round(r.width),
                        h: Math.round(r.height),
                        visible: !!(r.width && r.height)
                    };
                })
                .filter(x => x.visible && x.text)
                .slice(0, 300)"""
        )
        for item in elements:
            print(item)
        page.evaluate(
            """() => {
                const cards = Array.from(document.querySelectorAll('[class*="solutionCard"]'));
                const card = cards.find(el => (el.innerText || el.textContent || '').includes('丸友集'));
                if (!card) throw new Error('未找到丸友集卡片');
                const button = Array.from(card.querySelectorAll('taro-view-core, div, span'))
                    .find(el => (el.innerText || el.textContent || '').trim() === '申请开通');
                if (!button) throw new Error('未找到丸友集申请开通按钮');
                button.click();
            }"""
        )
        page.wait_for_timeout(3000)
        print("AFTER_APPLY_URL", page.url)
        print(page.locator("body").inner_text(timeout=10000)[:8000])
        page.screenshot(path=str(reports / "tenant-wanyouji-apply-probe.png"), full_page=True)
        page.screenshot(path=str(reports / "tenant-subscribe-probe.png"), full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
