from __future__ import annotations

import json
import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from e2e.pages.wanyouji_member_page import WanyoujiMemberData, WanyoujiMemberPage
from e2e.utils.verification_code import FeishuConfig, VerificationCodeProvider


OUT_DIR = Path("runtime/member_probe/sms_login_debug")


def main() -> None:
    load_dotenv()
    phone = os.getenv("E2E_MEMBER_DEBUG_PHONE", "").strip()
    role = os.getenv("E2E_MEMBER_DEBUG_ROLE", "打手").strip()
    if not phone:
        raise SystemExit("请设置 E2E_MEMBER_DEBUG_PHONE")
    provider = VerificationCodeProvider(
        mode=os.getenv("E2E_VERIFICATION_CODE_MODE", "feishu"),
        static_code=os.getenv("E2E_VERIFICATION_CODE_STATIC", ""),
        manual_code_file=os.getenv("E2E_MANUAL_CODE_FILE", "runtime/sms_code.txt"),
        manual_timeout_seconds=int(os.getenv("E2E_MANUAL_CODE_TIMEOUT_SECONDS", "180")),
        manual_poll_interval_seconds=int(os.getenv("E2E_MANUAL_CODE_POLL_INTERVAL_SECONDS", "2")),
        feishu_config=FeishuConfig(
            app_id=os.getenv("FEISHU_APP_ID", ""),
            app_secret=os.getenv("FEISHU_APP_SECRET", ""),
            chat_id=os.getenv("FEISHU_CHAT_ID", ""),
            timeout_seconds=int(os.getenv("FEISHU_TIMEOUT_SECONDS", "60")),
            poll_interval_seconds=int(os.getenv("FEISHU_POLL_INTERVAL_SECONDS", "3")),
        ),
    )
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        member_page = WanyoujiMemberPage(
            page,
            "https://test-lianlianyun.lianlianwz.com/home",
            code_provider=provider,
        )
        member = WanyoujiMemberData(phone=phone, password="test123456", role=role, name=f"DEBUG{role}")
        try:
            member_page.clear_desktop_login_state()
            member_page.goto(member_page.tenant_home_url.replace("/home", "/login"))
            member_page.wait_for_desktop_login_ready()
            member_page.click_text_on_page(page, ["验证码登录", "短信登录"])
            member_page.wait_for_desktop_login_ready()
            member_page.fill_page_input_on_page(page, ["手机号", "手机号码", "账号"], member.phone, required=True)
            dump(page, "01_输入手机号后")
            member_page.request_desktop_sms_code_with_graphic_retry(member.phone)
            dump(page, "02_获取短信后")
            member_page.fill_desktop_sms_code(member.phone)
            member_page.check_login_agreement_if_present()
            dump(page, "03_填短信并勾协议后")
            member_page.click_desktop_sms_login_submit()
            page.wait_for_timeout(5000)
            dump(page, "04_点击登录后")
        finally:
            context.close()
            browser.close()


def dump(page, name: str) -> None:
    payload = {
        "url": page.url,
        "text": safe_text(page)[:3000],
        "inputs": page.evaluate(
            """() => Array.from(document.querySelectorAll('input, textarea'))
              .map((el, index) => {
                const r = el.getBoundingClientRect();
                return {
                  index,
                  id: el.id || '',
                  type: el.getAttribute('type') || '',
                  placeholder: el.getAttribute('placeholder') || '',
                  value: el.value || '',
                  checked: Boolean(el.checked),
                  disabled: Boolean(el.disabled),
                  className: String(el.className || ''),
                  rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                  visible: r.width > 0 && r.height > 0,
                  itemText: (el.closest('label, div, form')?.innerText || '').trim().slice(0, 500),
                };
              })"""
        ),
        "buttons": page.evaluate(
            """() => Array.from(document.querySelectorAll('button, taro-button-core, div, span'))
              .map((el, index) => {
                const r = el.getBoundingClientRect();
                return {
                  index,
                  tag: el.tagName,
                  text: (el.innerText || el.textContent || '').trim().slice(0, 120),
                  disabled: Boolean(el.disabled) || el.getAttribute('aria-disabled') === 'true',
                  className: String(el.className || ''),
                  rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                  visible: r.width > 0 && r.height > 0,
                };
              })
              .filter(item => item.visible && item.text)"""
        ),
    }
    (OUT_DIR / f"{name}.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    page.screenshot(path=OUT_DIR / f"{name}.png", full_page=True)


def safe_text(page) -> str:
    try:
        return page.locator("body").inner_text(timeout=5000)
    except Exception as exc:
        return f"<无法读取页面文本：{exc}>"


if __name__ == "__main__":
    main()
