from __future__ import annotations

import json
import sys
from pathlib import Path

from playwright.sync_api import sync_playwright

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

from e2e.conftest import E2ESettings
from e2e.pages.product_solution_admin_page import ProductSolutionAdminPage


TARGET_PRODUCT_KEYWORDS = ["自动化产品编辑_", "自动化产品_", "自动化产品"]
OUTPUT_PATH = Path("runtime/prodsol_flow_006_modal_probe.json")


def main() -> None:
    settings = E2ESettings(
        tenant_base_url="https://test-lianlianyun.lianlianwz.com",
        tenant_home_url="https://test-lianlianyun.lianlianwz.com/home",
        admin_url="https://test-saas-adminui.lianlianwz.com/pages/home/index",
        admin_username="wangss",
        admin_password="123456",
        register_password="test123456",
        phone_prefix="19",
        max_register_attempts=5,
        enterprise_name_prefix="E2E测试企业",
        verification_code_mode="feishu",
        verification_code_static="",
        manual_code_file="runtime/sms_code.txt",
        manual_code_timeout_seconds=180,
        manual_code_poll_interval_seconds=2,
        image_captcha_mode="ddddocr",
        feishu_app_id="",
        feishu_app_secret="",
        feishu_chat_id="",
        feishu_timeout_seconds=60,
        feishu_poll_interval_seconds=3,
        certified_tenant_phone="19361091624",
        certified_tenant_password="test123456",
        certified_tenant_enterprise_name="E2E测试企业0603174618802",
        certified_tenant_merchant_id="99",
        wanyouji_product_id="12",
        wanzhanggui_product_id="15",
        wanzhanggui_tenant_phone="19147509308",
        wanzhanggui_tenant_password="test123456",
        viewport_width=1920,
        viewport_height=1080,
    )
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True, args=["--window-size=1920,1080"])
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        admin = ProductSolutionAdminPage(page, settings.admin_url)
        admin.login(settings.admin_username, settings.admin_password)
        admin.open_product_edit_version_step_by_keywords(TARGET_PRODUCT_KEYWORDS)
        admin.open_first_subscription_version_edit()
        admin.scroll_subscription_version_modal_to_bottom()
        try:
            admin._click_first_available_subscription_app_version_config_action()
            page.wait_for_timeout(1000)
        except Exception as exc:
            print(f"click_add_failed={exc}")
        page.wait_for_timeout(1000)

        payload = page.evaluate(
            """() => {
              const modals = Array.from(document.querySelectorAll('.ant-modal'))
                .filter(element => element.offsetParent !== null);
              return modals.map((modal, modalIndex) => {
                const rows = Array.from(modal.querySelectorAll('.ant-table-row, tr, .ant-card, .ant-list-item'))
                  .filter(row => row.offsetParent !== null)
                  .map((row, rowIndex) => ({
                    rowIndex,
                    text: (row.innerText || row.textContent || '').replace(/\\s+/g, ' ').trim(),
                    html: row.outerHTML,
                    directButtons: Array.from(row.querySelectorAll('button'))
                      .filter(element => element.offsetParent !== null)
                      .map((element, index) => ({
                        index,
                        text: (element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim(),
                        className: String(element.className || ''),
                        disabled: !!element.disabled,
                      })),
                    buttons: Array.from(row.querySelectorAll('button, a, span'))
                      .filter(element => element.offsetParent !== null)
                      .map(element => (element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim())
                      .filter(Boolean),
                  }));
                const buttons = Array.from(modal.querySelectorAll('button, a, span'))
                  .filter(element => element.offsetParent !== null)
                  .map((element, index) => ({
                    index,
                    text: (element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim(),
                    tag: element.tagName,
                    className: String(element.className || ''),
                    parentText: (element.parentElement?.innerText || element.parentElement?.textContent || '').replace(/\\s+/g, ' ').trim(),
                    parentHtml: element.parentElement?.outerHTML || '',
                    grandParentText: (element.parentElement?.parentElement?.innerText || element.parentElement?.parentElement?.textContent || '').replace(/\\s+/g, ' ').trim(),
                    grandParentHtml: element.parentElement?.parentElement?.outerHTML || '',
                  }))
                  .filter(item => item.text);
                return {
                  modalIndex,
                  text: (modal.innerText || modal.textContent || '').replace(/\\s+/g, ' ').trim(),
                  rows,
                  buttons,
                };
              });
            }"""
        )
        OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
        OUTPUT_PATH.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
        print(OUTPUT_PATH)
        browser.close()


if __name__ == "__main__":
    main()
