#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
目标平台元素选择器分析脚本

分析目标平台的页面元素，提取更精确的选择器。
"""

from playwright.sync_api import sync_playwright
import json
import sys

BASE_URL = "https://192.168.5.44"


def analyze_page(page, page_name: str):
    """分析页面元素"""
    print(f"\n{'='*60}")
    print(f"Analyzing: {page_name}")
    print(f"{'='*60}")

    result = {
        "page": page_name,
        "url": page.url,
        "inputs": [],
        "buttons": [],
        "forms": [],
        "tables": [],
        "important_elements": []
    }

    # 分析输入框
    inputs = page.query_selector_all('input')
    for inp in inputs:
        try:
            info = {
                "type": inp.get_attribute('type') or 'text',
                "placeholder": inp.get_attribute('placeholder') or '',
                "name": inp.get_attribute('name') or '',
                "id": inp.get_attribute('id') or '',
                "class": (inp.get_attribute('class') or '').split()[:3],
            }
            result["inputs"].append(info)
            print(f"Input: type={info['type']}, placeholder={info['placeholder'][:30]}")
        except:
            pass

    # 分析按钮
    buttons = page.query_selector_all('button, .el-button, [role="button"]')
    for btn in buttons:
        try:
            text = btn.inner_text().strip()[:30]
            if text:
                info = {
                    "text": text,
                    "class": (btn.get_attribute('class') or '').split()[:3],
                    "type": btn.get_attribute('type') or 'button',
                }
                result["buttons"].append(info)
                print(f"Button: text={info['text']}")
        except:
            pass

    # 分析表单
    forms = page.query_selector_all('form, .el-form')
    for form in forms:
        try:
            info = {
                "class": (form.get_attribute('class') or '').split()[:3],
                "id": form.get_attribute('id') or '',
            }
            result["forms"].append(info)
        except:
            pass

    # 分析表格
    tables = page.query_selector_all('table, .el-table')
    for table in tables:
        try:
            info = {
                "class": (table.get_attribute('class') or '').split()[:3],
            }
            result["tables"].append(info)
        except:
            pass

    return result


def main():
    """主函数"""
    all_pages_info = {}

    with sync_playwright() as p:
        # 启动浏览器（忽略证书错误）
        browser = p.chromium.launch(
            headless=True,
            args=['--ignore-certificate-errors']
        )
        context = browser.new_context(
            ignore_https_errors=True,
            viewport={"width": 1920, "height": 1080}
        )
        page = context.new_page()
        page.set_default_timeout(30000)

        try:
            # 1. 登录页
            print("\n[1] Visiting login page...")
            page.goto(BASE_URL, wait_until="networkidle")
            page.wait_for_timeout(2000)
            all_pages_info["login"] = analyze_page(page, "Login Page")

            # 执行登录（如果需要继续分析其他页面）
            # 填写表单
            inputs = page.query_selector_all('input:visible')
            for inp in inputs:
                inp_type = inp.get_attribute('type') or 'text'
                inp_placeholder = inp.get_attribute('placeholder') or ''
                if inp_type == 'text' and ('用户' in inp_placeholder or '手机' in inp_placeholder):
                    inp.fill('admin@xty')
                elif inp_type == 'password':
                    inp.fill('Ubains@13579')
                elif '验证' in inp_placeholder:
                    inp.fill('csba')

            # 点击登录
            buttons = page.query_selector_all('button')
            for btn in buttons:
                if '登录' in btn.inner_text():
                    btn.click()
                    break

            page.wait_for_timeout(3000)

            # 处理协议弹窗
            try:
                dialogs = page.query_selector_all('.el-dialog button, [role="dialog"] button')
                for db in dialogs:
                    if '确定' in db.inner_text() and db.is_visible():
                        db.click()
                        break
            except:
                pass

            page.wait_for_timeout(5000)

            # 2. 首页
            print("\n[2] Visiting home page...")
            all_pages_info["home"] = analyze_page(page, "Home Page")

            # 3. 会议预约页
            print("\n[3] Visiting meeting reservation page...")
            page.goto(f"{BASE_URL}/#/meeting/reservation", wait_until="networkidle")
            page.wait_for_timeout(2000)
            all_pages_info["meeting_reservation"] = analyze_page(page, "Meeting Reservation")

            # 4. 会议室列表
            print("\n[4] Visiting meeting room list...")
            page.goto(f"{BASE_URL}/#/meeting/room", wait_until="networkidle")
            page.wait_for_timeout(2000)
            all_pages_info["meeting_room_list"] = analyze_page(page, "Meeting Room List")

            # 5. 会议列表
            print("\n[5] Visiting meeting list...")
            page.goto(f"{BASE_URL}/#/meeting/list", wait_until="networkidle")
            page.wait_for_timeout(2000)
            all_pages_info["meeting_list"] = analyze_page(page, "Meeting List")

        except Exception as e:
            print(f"Error: {str(e)}")

        finally:
            browser.close()

    # 输出汇总
    print("\n" + "="*60)
    print("Summary")
    print("="*60)
    for page_name, info in all_pages_info.items():
        print(f"\n{page_name}:")
        print(f"  Inputs: {len(info['inputs'])}")
        print(f"  Buttons: {len(info['buttons'])}")
        print(f"  Forms: {len(info['forms'])}")
        print(f"  Tables: {len(info['tables'])}")

    return all_pages_info


if __name__ == "__main__":
    result = main()

    # 保存结果
    output_file = "element_selectors.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=2, ensure_ascii=False)
    print(f"\nResults saved to: {output_file}")