from __future__ import annotations

from playwright.sync_api import sync_playwright


def main() -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        logs: list[str] = []

        def log_response(response):
            url = response.url
            if any(key in url.lower() for key in ["product", "apply", "subscribe", "merchant"]):
                logs.append(f"{response.status} {response.request.method} {url}")

        page.on("response", log_response)
        page.on("console", lambda message: logs.append(f"CONSOLE {message.type}: {message.text}"))

        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(2000)
        page.goto("https://test-lianlianyun.lianlianwz.com/scheme", wait_until="domcontentloaded")
        page.wait_for_timeout(3000)

        print("BEFORE")
        print(page.evaluate(
            """() => {
                const cards = Array.from(document.querySelectorAll('[class*="solutionCard"]'))
                    .filter(el => !String(el.className).includes('solutionCards'));
                const card = cards.find(el => (el.innerText || el.textContent || '').includes('丸友集'));
                return card ? (card.innerText || card.textContent || '') : '';
            }"""
        ))

        page.evaluate(
            """() => {
                const cards = Array.from(document.querySelectorAll('[class*="solutionCard"]'))
                    .filter(el => !String(el.className).includes('solutionCards'));
                const card = cards.find(el => (el.innerText || el.textContent || '').includes('丸友集'));
                const target = card && Array.from(card.querySelectorAll('taro-view-core, div, span, button'))
                    .find(el => String(el.className).includes('useButton___'));
                if (target) target.scrollIntoView({ block: 'center', inline: 'center' });
            }"""
        )
        page.wait_for_timeout(300)

        target_box = page.evaluate(
            """() => {
                const cards = Array.from(document.querySelectorAll('[class*="solutionCard"]'))
                    .filter(el => !String(el.className).includes('solutionCards'));
                const card = cards.find(el => (el.innerText || el.textContent || '').includes('丸友集'));
                if (!card) return null;
                const target = Array.from(card.querySelectorAll('taro-view-core, div, span, button'))
                    .find(el => {
                        const text = (el.innerText || el.textContent || '').trim();
                        const cls = String(el.className);
                        const r = el.getBoundingClientRect();
                        return r.width > 0 && r.height > 0 && cls.includes('useButton___');
                    });
                if (!target) return null;
                const r = target.getBoundingClientRect();
                return {
                    x: r.x,
                    y: r.y,
                    width: r.width,
                    height: r.height,
                    text: (target.innerText || target.textContent || '').trim(),
                    className: String(target.className)
                };
            }"""
        )
        print("TARGET", target_box)
        if target_box:
            page.mouse.click(target_box["x"] + target_box["width"] / 2, target_box["y"] + target_box["height"] / 2)
        page.wait_for_timeout(5000)

        print("AFTER")
        print(page.locator("body").inner_text(timeout=10000)[:5000])
        print("LOGS")
        for item in logs:
            print(item)
        page.screenshot(path="reports/tenant-wanyouji-apply-submit-probe.png", full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
