from __future__ import annotations

import os
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright


load_dotenv()

TENANT_HOME_URL = os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home")


def login_and_select_main(page, phone: str, password: str) -> None:
    page.goto(TENANT_HOME_URL.replace("/home", "/login"), wait_until="domcontentloaded")
    page.locator("#password_login_phone").fill(phone)
    page.locator("#password_login_password").fill(password)
    page.get_by_text("登 录", exact=True).click()
    page.wait_for_load_state("domcontentloaded")
    page.wait_for_timeout(2000)
    if "/account/select" in page.url or "选择账号" in page.locator("body").inner_text(timeout=3000):
        box = page.evaluate(
            """() => {
                const candidates = Array.from(document.querySelectorAll('taro-view-core, div'))
                  .map(el => ({ text: el.innerText || el.textContent || '', r: el.getBoundingClientRect() }))
                  .filter(item => item.text.includes('主账号') && !item.text.includes('子账号'))
                  .filter(item => item.r.width > 300 && item.r.width < 800 && item.r.height > 50 && item.r.height < 140)
                  .sort((a, b) => (a.r.width * a.r.height) - (b.r.width * b.r.height));
                const target = candidates[0];
                if (!target) return null;
                return { x: target.r.x, y: target.r.y, width: target.r.width, height: target.r.height };
            }"""
        )
        if box:
            page.mouse.click(box["x"] + box["width"] - 30, box["y"] + box["height"] / 2)
            page.wait_for_load_state("domcontentloaded")
            page.wait_for_timeout(2000)
    body_text = page.locator("body").inner_text(timeout=5000)
    if "子账号" in body_text and "主账号" not in body_text:
        raise AssertionError(f"登录账号 {phone} 未进入主账号上下文，当前页面文本：{body_text[:500]}")


def click_solution_console(page, solution: str):
    page.goto(TENANT_HOME_URL.replace("/home", "/scheme"), wait_until="domcontentloaded")
    page.wait_for_timeout(3000)
    body = page.locator("body").inner_text(timeout=5000)
    print(f"[scheme before {solution}] {page.url}\n{body[:1200]}")
    box = page.evaluate(
        """solution => {
            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(solution));
            if (!card) return null;
            card.scrollIntoView({ block: 'center', inline: 'center' });
            const buttons = Array.from(card.querySelectorAll('taro-view-core, div, span, button'))
              .map(el => ({ text: (el.innerText || el.textContent || '').trim(), r: el.getBoundingClientRect(), cls: String(el.className) }))
              .filter(item => item.r.width > 0 && item.r.height > 0)
              .filter(item => item.text.includes('进入') || item.cls.includes('useButton'));
            buttons.sort((a, b) => (a.r.width * a.r.height) - (b.r.width * b.r.height));
            const target = buttons[0];
            if (!target) return null;
            return { x: target.r.x, y: target.r.y, width: target.r.width, height: target.r.height, text: target.text };
        }""",
        solution,
    )
    print(f"[button {solution}] {box}")
    if not box:
        return
    before = set(page.context.pages)
    page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
    page.wait_for_timeout(4000)
    new_pages = [p for p in page.context.pages if p not in before]
    target = new_pages[-1] if new_pages else page
    target.wait_for_load_state("domcontentloaded")
    target.wait_for_timeout(2000)
    out = Path("runtime/auth_probe")
    out.mkdir(parents=True, exist_ok=True)
    text = target.locator("body").inner_text(timeout=5000)
    (out / f"{solution}_console.txt").write_text(f"URL: {target.url}\n\n{text}", encoding="utf-8")
    target.screenshot(path=str(out / f"{solution}_console.png"), full_page=True)
    print(f"[console {solution}] {target.url}\n{text[:2000]}")


def main() -> None:
    accounts = [
        ("丸友集", os.getenv("E2E_CERTIFIED_TENANT_PHONE", "19361091624"), os.getenv("E2E_CERTIFIED_TENANT_PASSWORD", "test123456")),
        ("丸掌柜", os.getenv("E2E_WANZHANGGUI_TENANT_PHONE", "15555555555"), os.getenv("E2E_WANZHANGGUI_TENANT_PASSWORD", "wss123456")),
    ]
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        for solution, phone, password in accounts:
            context = browser.new_context(viewport={"width": 1440, "height": 900})
            page = context.new_page()
            login_and_select_main(page, phone, password)
            click_solution_console(page, solution)
            context.close()
        browser.close()


if __name__ == "__main__":
    main()
