from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import json
import sys

from playwright.sync_api import sync_playwright

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

from e2e.pages.product_solution_admin_page import ProductSolutionAdminPage


@dataclass(frozen=True)
class Settings:
    admin_url: str = "https://test-saas-adminui.lianlianwz.com/pages/home/index"
    admin_username: str = "wangss"
    admin_password: str = "123456"


def main() -> None:
    settings = Settings()
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    out_dir = Path("runtime")
    out_dir.mkdir(exist_ok=True)
    json_path = out_dir / f"prodsol_menu_create_modal_{timestamp}.json"
    screenshot_path = out_dir / f"prodsol_menu_create_modal_{timestamp}.png"

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=100)
        page = browser.new_page(viewport={"width": 1920, "height": 1080})
        admin = ProductSolutionAdminPage(page, settings.admin_url)
        admin.login(settings.admin_username, settings.admin_password)
        admin.open_product_menu_config_by_keywords(["自动化产品编辑", "自动化产品a", "自动化产品"])
        modal = admin._active_solution_menu_modal()
        admin.click_button_in_container(modal, ["创建菜单", "新建菜单", "新增菜单"], timeout=5000)
        page.wait_for_timeout(1500)

        summary = page.evaluate(
            """() => {
              const compact = (value) => (value || '').replace(/\\s+/g, ' ').trim();
              const visible = (element) => !!element && (
                element.offsetParent !== null ||
                element.closest('.ant-select, .ant-input-affix-wrapper')
              );
              const root = Array.from(document.querySelectorAll('.ant-modal, .ant-drawer'))
                .reverse()
                .find(element => element.offsetParent !== null);
              if (!root) return { error: 'modal not found' };
              const describe = (element) => {
                const rect = element.getBoundingClientRect();
                const parent = element.parentElement;
                const grand = parent && parent.parentElement;
                const formItem = element.closest('.ant-form-item, .ant-row, .ant-col, [class*="form"]');
                return {
                  tag: element.tagName,
                  type: element.getAttribute('type'),
                  role: element.getAttribute('role'),
                  className: String(element.className || ''),
                  placeholder: element.getAttribute('placeholder'),
                  ariaLabel: element.getAttribute('aria-label'),
                  name: element.getAttribute('name'),
                  value: element.value,
                  checked: element.checked,
                  text: compact(element.innerText || element.textContent || ''),
                  rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
                  parentText: compact(parent?.innerText || parent?.textContent || '').slice(0, 500),
                  grandParentText: compact(grand?.innerText || grand?.textContent || '').slice(0, 500),
                  formItemText: compact(formItem?.innerText || formItem?.textContent || '').slice(0, 800),
                  outerHTML: element.outerHTML.slice(0, 800),
                };
              };
              return {
                text: compact(root.innerText || '').slice(0, 5000),
                controls: Array.from(root.querySelectorAll('input, textarea, button, select, [contenteditable], .ant-select, .ant-radio-wrapper, .ant-checkbox-wrapper'))
                  .filter(visible)
                  .map(describe),
              };
            }"""
        )
        page.screenshot(path=str(screenshot_path), full_page=True)
        json_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"screenshot: {screenshot_path}")
        print(f"json: {json_path}")
        print(json.dumps(summary, ensure_ascii=False, indent=2)[:8000])
        browser.close()


if __name__ == "__main__":
    main()
