#!/usr/bin/env python3
"""
JoySpace WS 编辑客户端 — 通过 Playwright 直接操作浏览器中的 Slate/Yjs 编辑器。

基于 joyspace-write-doc 的 proven 方案（scroll+click+End+Enter+type），
增加 WS 帧监控和更完善的验证机制。

关键认知：JoySpace 使用 virtual-caret 架构
  - Preview 层 (contenteditable="false"): 渲染实际文档内容
  - Editable 层 (contenteditable="true"): 独立的最小编辑器，处理输入
  - 必须先点击编辑器中心激活 virtual-caret-input textarea
  - 然后滚动+点击末尾节点 + End+Enter+type 触发 OT 操作

支持的操作：
  - append_text: 在文档末尾追加文本
  - insert_text: 在光标位置插入文本
  - get_content: 读取当前文档内容
  - replace_all: 替换整个文档内容
"""

import asyncio
import json
import sys
import time
from pathlib import Path
from typing import Optional

sys.path.insert(0, str(Path(__file__).resolve().parent))
from api.gateway import JoySpaceClient

JOYSPACE_BASE = "https://joyspace.jd.com"
DEFAULT_WAIT_SAVE = 6.0

# macOS 用 Meta(Cmd) 作为修饰键，Windows/Linux 用 Control。
# headless chromium 里 Control 通常也能触发全选/跳转，但 Mac 可见浏览器下 Meta 更可靠。
_MOD = "Meta" if sys.platform == "darwin" else "Control"
SELECT_ALL = f"{_MOD}+a"
MOVE_TO_DOC_END = f"{_MOD}+End"
DEFAULT_SLOW_MO = 100

# ─── JS helpers (与 playwright_writer.py 保持一致) ───

_SCROLL_LAST_NODE_JS = """
() => {
    const ed = document.querySelector('[data-slate-editor]');
    if (!ed) return null;
    const nodes = ed.querySelectorAll('[data-slate-node="element"]');
    if (!nodes.length) return null;
    nodes[nodes.length-1].scrollIntoView({behavior:'instant', block:'center'});
    return nodes.length;
}
"""

_GET_LAST_NODE_BOX_JS = """
() => {
    const ed = document.querySelector('[data-slate-editor]');
    if (!ed) return null;
    const nodes = ed.querySelectorAll('[data-slate-node="element"]');
    if (!nodes.length) return null;
    const last = nodes[nodes.length-1];
    const r = last.getBoundingClientRect();
    return {x: r.left, y: r.top, w: r.width, h: r.height, inView: r.top >= 0 && r.top <= window.innerHeight};
}
"""

_GET_EDITOR_TAIL_JS = """
(n) => {
    const ed = document.querySelector('[data-slate-editor]');
    if (!ed) return '';
    return (ed.innerText || ed.textContent || '').slice(-n);
}
"""

_GET_CONTENT_JS = """
() => {
    const preview = document.querySelector('[data-slate-editor][contenteditable="false"]');
    const editable = document.querySelector('[data-slate-editor][contenteditable="true"]');
    return {
        previewText: (preview?.innerText || '').trim(),
        editableText: (editable?.innerText || '').trim(),
    };
}
"""


class JoySpaceWSEditor:
    """Edit JoySpace documents via Playwright with Yjs OT sync verification."""

    def __init__(self, sso_token: str = None, headless: bool = True):
        self.sso_token = sso_token or JoySpaceClient().sso_token
        self.headless = headless
        self._browser = None
        self._context = None
        self._page = None
        self._ws_sent = 0
        self._ws_sent_before_type = 0

    async def _ensure_browser(self):
        if self._browser:
            return
        try:
            from playwright.async_api import async_playwright
        except ImportError:
            raise RuntimeError("Playwright 未安装，请运行: pip install playwright && playwright install chromium")

        self._playwright = await async_playwright().start()

        browser = None
        last_err = None
        for channel in ["msedge", "chrome", "chromium"]:
            try:
                browser = await self._playwright.chromium.launch(
                    channel=channel, headless=self.headless, slow_mo=DEFAULT_SLOW_MO
                )
                break
            except Exception as e:
                last_err = e
                continue
        if not browser:
            try:
                browser = await self._playwright.chromium.launch(
                    headless=self.headless, slow_mo=DEFAULT_SLOW_MO
                )
            except Exception as e:
                await self._playwright.stop()
                self._playwright = None
                raise RuntimeError(f"浏览器启动失败: {e}。请安装 Playwright 浏览器: playwright install chromium")

        self._browser = browser
        self._context = await browser.new_context(viewport={"width": 1280, "height": 900})
        await self._context.add_cookies([{
            "name": "sso.jd.com",
            "value": self.sso_token,
            "domain": ".jd.com",
            "path": "/",
        }])
        self._page = await self._context.new_page()
        self._ws_sent = 0
        self._ws_sent_before_type = 0

        # Track WS frames
        def on_ws(ws):
            def on_sent(payload):
                self._ws_sent += 1
            ws.on("framesent", on_sent)

        self._page.on("websocket", on_ws)

    async def open_page(self, page_id: str, page_type: str = "document") -> dict:
        """Open a JoySpace page and wait for Yjs sync."""
        await self._ensure_browser()

        url_map = {
            "document": f"{JOYSPACE_BASE}/pages/{page_id}",
            "mind_map": f"{JOYSPACE_BASE}/mind/{page_id}",
            "blog": f"{JOYSPACE_BASE}/blogs/{page_id}",
        }
        url = url_map.get(page_type, f"{JOYSPACE_BASE}/pages/{page_id}")

        self._ws_sent = 0
        await self._page.goto(url, wait_until="domcontentloaded", timeout=30000)

        try:
            await self._page.wait_for_selector('[data-slate-editor]', timeout=20000)
        except Exception:
            await self.close()
            return {"success": False, "error": "文档编辑器加载超时，请检查链接是否正确、是否有编辑权限"}

        # Wait for Yjs sync (content appears in editor)
        await asyncio.sleep(3)

        # Get current content
        content = await self._page.evaluate(_GET_CONTENT_JS)

        return {
            "success": True,
            "content_length": len(content.get("previewText", "")),
            "content_preview": content.get("previewText", "")[:200],
        }

    async def get_content(self) -> dict:
        """Get the current document content."""
        return await self._page.evaluate(_GET_CONTENT_JS)

    async def append_text(self, text: str, wait_save: float = DEFAULT_WAIT_SAVE) -> dict:
        """Append text to the end of the document using keyboard simulation.

        Uses the proven approach from playwright_writer.py:
        1. Click editor center to activate virtual-caret-input textarea
        2. JS scrollIntoView last node
        3. Physical click on last node
        4. End + Enter + type
        5. Wait for Yjs OT sync and verify
        """
        page = self._page

        # ===== Step 1: Click editor center to activate virtual-caret-input =====
        editors = page.locator('[data-slate-editor]')
        count = await editors.count()
        if count == 0:
            return {"success": False, "error": "No editor found"}

        editor = editors.first
        box = await editor.bounding_box()
        if not box:
            return {"success": False, "error": "Editor bounding_box is empty"}

        viewport_h = (page.viewport_size or {"height": 900})["height"]
        click_y = min(box["y"] + 200, viewport_h - 20)
        click_x = box["x"] + box["width"] // 2
        await page.mouse.click(click_x, click_y)
        await asyncio.sleep(0.5)

        # ===== Step 2: JS scroll last node into view =====
        node_count = await page.evaluate(_SCROLL_LAST_NODE_JS)
        await asyncio.sleep(0.6)

        # ===== Step 3: Physical click on last node =====
        last_box = await page.evaluate(_GET_LAST_NODE_BOX_JS)
        if last_box and last_box.get("inView"):
            cx = last_box["x"] + 30
            cy = last_box["y"] + last_box["h"] / 2
            await page.mouse.click(cx, cy)
            await asyncio.sleep(0.5)
        else:
            await page.keyboard.press(MOVE_TO_DOC_END)
            await asyncio.sleep(0.3)

        # ===== Step 4: End + Enter, record WS frame count =====
        await page.keyboard.press("End")
        await page.keyboard.press("Enter")
        self._ws_sent_before_type = self._ws_sent

        # ===== Step 5: Type text line by line =====
        lines = text.split("\n")
        for i, line in enumerate(lines):
            if line:
                await page.keyboard.type(line, delay=0)
            if i < len(lines) - 1:
                await page.keyboard.press("Enter")
                await asyncio.sleep(0.05)

        # ===== Step 6: Wait for Yjs OT sync =====
        await asyncio.sleep(wait_save)

        # ===== Step 7: Verify =====
        new_frames = self._ws_sent - self._ws_sent_before_type

        verify_tail = text.replace("\n", "").strip()[-80:]
        editor_tail = await page.evaluate(_GET_EDITOR_TAIL_JS, 300)
        editor_tail_clean = (editor_tail or "").replace("\n", "").strip()

        result = {
            "ws_new_frames": new_frames,
            "node_count": node_count,
        }

        if verify_tail and verify_tail in editor_tail_clean:
            result["success"] = True
            result["verify"] = "text_match"
        elif new_frames > 0:
            result["success"] = True
            result["verify"] = "ws_frames_only"
        else:
            result["success"] = False
            result["verify"] = "unverified"
            result["error"] = "No WS frames sent and text not found in editor"

        return result

    async def insert_text_at_cursor(self, text: str, wait_save: float = DEFAULT_WAIT_SAVE) -> dict:
        """Insert text at the current cursor position using keyboard simulation."""
        if not self._page:
            return {"success": False, "error": "未打开任何页面，请先调用 open_page"}
        self._ws_sent_before_type = self._ws_sent

        await self._page.keyboard.type(text, delay=0)
        await asyncio.sleep(wait_save)

        new_frames = self._ws_sent - self._ws_sent_before_type
        return {"success": new_frames > 0, "ws_new_frames": new_frames}

    async def replace_all(self, text: str, wait_save: float = DEFAULT_WAIT_SAVE) -> dict:
        """Replace the entire document content by selecting all and typing new text."""
        page = self._page

        # Activate editor first
        editors = page.locator('[data-slate-editor]')
        editor = editors.first
        box = await editor.bounding_box()
        if not box:
            return {"success": False, "error": "Editor bounding_box is empty"}

        viewport_h = (page.viewport_size or {"height": 900})["height"]
        click_y = min(box["y"] + 200, viewport_h - 20)
        click_x = box["x"] + box["width"] // 2
        await page.mouse.click(click_x, click_y)
        await asyncio.sleep(0.5)

        self._ws_sent_before_type = self._ws_sent

        # Select all and delete
        await page.keyboard.press(SELECT_ALL)
        await asyncio.sleep(0.2)
        await page.keyboard.press("Delete")
        await asyncio.sleep(0.5)

        # Type new content
        lines = text.split("\n")
        for i, line in enumerate(lines):
            if line:
                await page.keyboard.type(line, delay=0)
            if i < len(lines) - 1:
                await page.keyboard.press("Enter")
                await asyncio.sleep(0.05)

        await asyncio.sleep(wait_save)

        new_frames = self._ws_sent - self._ws_sent_before_type

        # Verify content
        content = await page.evaluate(_GET_CONTENT_JS)
        preview_text = content.get("previewText", "").strip()
        typed_text = text.strip()

        result = {"ws_new_frames": new_frames}
        if typed_text and typed_text[:80] in preview_text:
            result["success"] = True
            result["verify"] = "text_match"
        elif new_frames > 0:
            result["success"] = True
            result["verify"] = "ws_frames_only"
        else:
            result["success"] = False
            result["verify"] = "unverified"

        return result

    async def close(self):
        if self._browser:
            await self._browser.close()
            self._browser = None
        if self._playwright:
            await self._playwright.stop()
            self._playwright = None

    async def __aenter__(self):
        return self

    async def __aexit__(self, *args):
        await self.close()


# ===== CLI interface =====

async def main_async():
    import argparse
    parser = argparse.ArgumentParser(description="JoySpace WS Editor")
    parser.add_argument("--token", help="SSO token")
    parser.add_argument("--page-id", required=True, help="Page ID to edit")
    parser.add_argument("--page-type", default="document")
    parser.add_argument("--action", default="get_content",
                        choices=["get_content", "append_text", "insert_text", "replace_all"])
    parser.add_argument("--text", help="Text to insert/append")
    parser.add_argument("--wait", type=float, default=DEFAULT_WAIT_SAVE, help="Wait time for WS sync")
    parser.add_argument("--no-headless", action="store_true")
    args = parser.parse_args()

    editor = JoySpaceWSEditor(sso_token=args.token, headless=not args.no_headless)
    try:
        open_result = await editor.open_page(args.page_id, args.page_type)
        print(f"Open: {json.dumps(open_result, ensure_ascii=False, indent=2)}")

        if not open_result.get("success"):
            return

        if args.action == "get_content":
            result = await editor.get_content()
        elif args.action == "append_text":
            if not args.text:
                print("Error: --text required")
                return
            result = await editor.append_text(args.text, args.wait)
        elif args.action == "insert_text":
            if not args.text:
                print("Error: --text required")
                return
            result = await editor.insert_text_at_cursor(args.text, args.wait)
        elif args.action == "replace_all":
            if not args.text:
                print("Error: --text required")
                return
            result = await editor.replace_all(args.text, args.wait)
        else:
            return

        print(f"Result: {json.dumps(result, ensure_ascii=False, indent=2)}")

    finally:
        await editor.close()


if __name__ == "__main__":
    asyncio.run(main_async())
