from __future__ import annotations

import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

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

from e2e.pages.admin_application_page import AdminApplicationPage


load_dotenv()
sys.stdout.reconfigure(encoding="utf-8")
OUT_DIR = Path("runtime/wanzhanggui_approval_probe")


def dump(page, name: str) -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    text = page.locator("body").inner_text(timeout=5000)
    inputs = page.evaluate(
        """() => Array.from(document.querySelectorAll('input, textarea')).map(el => ({
            placeholder: el.getAttribute('placeholder') || '',
            value: el.value || '',
            type: el.getAttribute('type') || '',
            rect: (() => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()
        }))"""
    )
    (OUT_DIR / f"{name}.txt").write_text(f"URL: {page.url}\n\n{text}\n\nINPUTS:\n{inputs}", encoding="utf-8")
    page.screenshot(path=str(OUT_DIR / f"{name}.png"), full_page=True)
    print(f"[{name}] {page.url}\n{text[:2500]}\nINPUTS: {inputs}")


def main() -> None:
    enterprise_name = os.getenv("E2E_PROBE_ENTERPRISE_NAME", "E2E测试企业0604142512528")
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        admin = AdminApplicationPage(page, os.getenv("ADMIN_URL", "https://test-saas-adminui.lianlianwz.com/pages/home/index"))
        admin.login(os.getenv("ADMIN_USERNAME", "wangss"), os.getenv("ADMIN_PASSWORD", "123456"))
        admin.open_application_request_list()
        dump(page, "application_list_initial")
        admin.search_product_application(keyword=enterprise_name)
        dump(page, "application_list_search_enterprise")
        admin.approve_product_application(enterprise_name, "丸掌柜", product_id=os.getenv("E2E_WANZHANGGUI_PRODUCT_ID", "15"))
        browser.close()


if __name__ == "__main__":
    main()
