#!/usr/bin/env python3
"""
JoySpace 表格超链接提取器 — 通过 Playwright 读取 WPS 在线表格 iframe 中的超链接。

背景：
  JoySpace 传统表格(pageType=18)由 WPS 在线组件渲染在跨域 iframe
  (joyspace-office.jd.com) 中。超链接地址只存在 WPS 的数据模型里，
  REST API (sheets.getEtRangeData) 只返回单元格显示文本，不返回链接地址。

方案：
  playwright headless 启动浏览器 → 注入 SSO cookie → 打开表格页 →
  定位跨域 office iframe (page.frames 遍历, CDP 不受同源策略限制) →
  等待 WPSOpenApi SDK 就绪 → 在 iframe 内执行异步 Proxy API 读取
  ActiveSheet.Hyperlinks 集合，拿到 address/text/row/col。

参考 ws_editor_client.JoySpaceWSEditor 的浏览器启动模式，但本类专门处理
WPS 表格 iframe，不复用 Slate 文档编辑逻辑。
"""

from __future__ import annotations

import asyncio
import sys
from pathlib import Path

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

JOYSPACE_BASE = "https://joyspace.jd.com"
OFFICE_FRAME_HOST = "joyspace-office.jd.com"

# WPS SDK 就绪轮询参数
_OFFICE_FRAME_TIMEOUT = 20      # 等 office iframe 出现的最长秒数
_WPS_API_READY_TIMEOUT = 40     # 等 WPSOpenApi.Application 可用的最长秒数
_WPS_POLL_INTERVAL = 2          # 轮询间隔


class SheetLinkExtractor:
    """通过 Playwright 打开 JoySpace 表格，读取其中所有超链接。

    用法（async）:
        async with SheetLinkExtractor(sso_token=...) as ex:
            links = await ex.extract(page_id)
    """

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

    async def __aenter__(self):
        return self

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

    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)
                break
            except Exception as e:
                last_err = e
                continue
        if not browser:
            try:
                browser = await self._playwright.chromium.launch(headless=self.headless)
            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()

    async def close(self):
        if self._browser:
            try:
                await self._browser.close()
            except Exception:
                pass
            self._browser = None
        if self._playwright:
            try:
                await self._playwright.stop()
            except Exception:
                pass
            self._playwright = None

    async def _find_office_frame(self, timeout: float = _OFFICE_FRAME_TIMEOUT):
        """轮询 page.frames，找到 WPS 在线表格 iframe。"""
        elapsed = 0.0
        while elapsed < timeout:
            for f in self._page.frames:
                if OFFICE_FRAME_HOST in (f.url or ""):
                    return f
            await asyncio.sleep(0.5)
            elapsed += 0.5
        return None

    async def _wait_wps_api_ready(self, frame, timeout: float = _WPS_API_READY_TIMEOUT) -> bool:
        """轮询等待 window.WPSOpenApi.Application 可用，再 await load promise。"""
        elapsed = 0.0
        while elapsed < timeout:
            ready = await frame.evaluate(
                "() => !!(window.WPSOpenApi && window.WPSOpenApi.Application)"
            )
            if ready:
                # await 两个 load promise 确保 SDK 完全就绪
                try:
                    await frame.evaluate(
                        """async () => {
                            const w = window.WPSOpenApi;
                            if (w && w.advancedApiLoadPromise) await w.advancedApiLoadPromise;
                            if (w && w.commonApiLoadPromise) await w.commonApiLoadPromise;
                        }"""
                    )
                except Exception:
                    pass
                return True
            await asyncio.sleep(_WPS_POLL_INTERVAL)
            elapsed += _WPS_POLL_INTERVAL
        return False

    async def extract(self, page_id: str, worksheet_id: str | int | None = None) -> list[dict]:
        """提取表格超链接，返回 [{row, col, address, text, worksheet}, ...]。

        Args:
            page_id: 表格页面 ID
            worksheet_id: 可选，指定工作表。WPS Worksheets.Item 用连续 index(1,2,3)，
                非 getEtWorksheets 的 sheetId。传 None 则遍历所有用户工作表。
                支持传 int index 或 str 数字。
        注意：WPS 在线表格懒加载，每个 sheet 必须 Activate() 后轮询等待 Hyperlinks 可读。
        """
        await self._ensure_browser()

        await self._page.goto(
            f"{JOYSPACE_BASE}/sheets/{page_id}",
            wait_until="domcontentloaded",
            timeout=60000,
        )

        office_frame = await self._find_office_frame()
        if not office_frame:
            raise RuntimeError(
                f"未找到 WPS office iframe ({OFFICE_FRAME_HOST})，页面可能未加载完成或非传统表格"
            )

        if not await self._wait_wps_api_ready(office_frame):
            raise RuntimeError("WPSOpenApi.Application 等待超时，SDK 未就绪")

        # 读 Hyperlinks（遍历所有 sheet 或指定 sheet，每个 Activate + 轮询等待）
        target_idx = None
        if worksheet_id is not None:
            try:
                target_idx = int(worksheet_id)
            except (ValueError, TypeError):
                target_idx = None

        js_code = """async (targetIdx) => {
            const out = {sheets: [], error: null};
            try {
                const A = window.WPSOpenApi.Application;
                const sheets = await A.Worksheets;
                const total = await sheets.Count;
                out.total = total;
                const idxList = targetIdx ? [targetIdx] : Array.from({length: total}, (_, i) => i + 1);
                for (const idx of idxList) {
                    try {
                        const sh = await sheets.Item(idx);
                        const name = await sh.Name;
                        // 跳过 WPS 内部保留表
                        if (String(name).startsWith("WpsReserved")) {
                            out.sheets.push({idx, name, skipped: true});
                            continue;
                        }
                        // Activate 触发懒加载
                        try { await sh.Activate(); } catch (e) {}
                        // 固定等待让懒加载完成（WPS 表格数据异步加载，Count 不稳定，
                        // 实测固定等 6s 比轮询稳定，避免读到部分加载的数据）
                        await new Promise(r => setTimeout(r, 6000));
                        // 轮询等待 Hyperlinks 可读（最多 15s，兜底异常）
                        let hl = null, hcnt = null, waited = 0;
                        while (waited < 15) {
                            try {
                                hl = await sh.Hyperlinks;
                                hcnt = await hl.Count;
                                break;
                            } catch (e) {
                                await new Promise(r => setTimeout(r, 1000));
                                waited++;
                            }
                        }
                        if (hcnt === null) {
                            out.sheets.push({idx, name, error: "Hyperlinks 等待超时（sheet 可能未加载）", waited});
                            continue;
                        }
                        const links = [];
                        for (let i = 1; i <= hcnt; i++) {
                            const h = await hl.Item(i);
                            const addr = await h.Address;
                            if (!addr) continue;
                            const rng = await h.Range;
                            let row = null, col = null;
                            try { row = await rng.Row; } catch (_) {}
                            try { col = await rng.Column; } catch (_) {}
                            let txt = "";
                            try { txt = await h.TextToDisplay; } catch (_) {}
                            links.push({row, col, address: addr, text: String(txt || "").slice(0, 200)});
                        }
                        out.sheets.push({idx, name, count: hcnt, links});
                    } catch (e) {
                        out.sheets.push({idx, error: e.message});
                    }
                }
            } catch (e) {
                out.error = e.message;
            }
            return out;
        }"""

        data = await office_frame.evaluate(js_code, target_idx)

        if data.get("error"):
            raise RuntimeError(f"WPS Hyperlinks 读取失败: {data['error']}")

        # 拍平所有 sheet 的 links，加 worksheet 字段
        result = []
        for s in data.get("sheets", []):
            if s.get("skipped") or s.get("error") or not s.get("links"):
                continue
            for item in s["links"]:
                result.append({
                    "row": item.get("row"),
                    "col": item.get("col"),
                    "address": item.get("address"),
                    "text": item.get("text", ""),
                    "worksheet": s.get("name"),
                    "worksheet_index": s.get("idx"),
                })
        return result


def _run_async(coro):
    """Run an async coroutine from sync context (复用 doc_editor 模式)."""
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None
    if loop and loop.is_running():
        import concurrent.futures
        with concurrent.futures.ThreadPoolExecutor() as pool:
            return pool.submit(asyncio.run, coro).result()
    return asyncio.run(coro)


def extract_links_sync(sso_token: str, page_id: str, headless: bool = True,
                       worksheet_id: str | int | None = None) -> list[dict]:
    """同步入口：供 ACTION_MAP 的 action 函数直接调用。

    worksheet_id: WPS Worksheets.Item 的连续 index(1,2,3...)，非 sheetId。
    传 None 遍历所有用户工作表。
    """
    async def _run():
        async with SheetLinkExtractor(sso_token=sso_token, headless=headless) as ex:
            return await ex.extract(page_id, worksheet_id=worksheet_id)
    return _run_async(_run())


if __name__ == "__main__":
    # 手动测试入口: python sheet_link_extractor.py <page_id> [--worksheet INDEX]
    import argparse, json
    parser = argparse.ArgumentParser(description="提取 JoySpace 表格超链接")
    parser.add_argument("page_id", help="表格 page_id")
    parser.add_argument("--token", help="SSO Token")
    parser.add_argument("--worksheet", help="工作表 index (WPS连续index,1起)，不传则遍历全部")
    parser.add_argument("--no-headless", action="store_true")
    args = parser.parse_args()

    try:
        if sys.stdout and hasattr(sys.stdout, "reconfigure"):
            sys.stdout.reconfigure(encoding="utf-8")
    except Exception:
        pass

    try:
        links = extract_links_sync(
            args.token, args.page_id,
            headless=not args.no_headless,
            worksheet_id=args.worksheet,
        )
        print(json.dumps({"status": "success", "count": len(links), "links": links},
                         ensure_ascii=False, indent=2))
    except Exception as e:
        print(json.dumps({"status": "error", "error": str(e)}, ensure_ascii=False, indent=2),
              file=sys.stderr)
        sys.exit(1)
