"""
WPS新表格 actions - 基于WPS WebOffice的表格操作

认证链路:
1. JoySpace getShiMoAuthorityInfo → 获取token
2. JoySpace /v2/pages/{id}/basic?embedLink=1 → 获取snapshotUrl（含_w_signature）
3. 加载WPS页面 → 获取csrf_token + cookies
4. 创建WPS session → 获取sessionId
5. 使用完整headers调用WPS API
"""

import json
import re

import requests

from .gateway import JoySpaceClient, JOYSPACE_API

WPS_BASE = "https://joyspace-office.jd.com"
WPS_APP_ID = "CZMXSYVJTQMNSBNJ-dc-appfile"
WPS_THIRD_APP_ID = "CZMXSYVJTQMNSBNJ"
WPS_FRONT_VER = "20260528151138-7f0614ba71"
WPS_GROUP = "20260605181705-fef0d60673"


class WPSClient:
    """WPS WebOffice API 客户端，处理完整的认证链路"""

    def __init__(self, joyspace_client: JoySpaceClient, page_id: str):
        self._js_client = joyspace_client
        self._page_id = page_id
        self._session = None
        self._csrf_token = ""
        self._full_url = ""
        self._w_signature = ""
        self._w_appid = WPS_APP_ID
        self._shimo_token = ""
        self._user_query = ""
        self._session_id = ""
        self._session_token = ""
        self._wps_file_id = ""
        self._initialized = False

    def _init_auth(self):
        if self._initialized:
            return

        # Step 1: Get ShiMo auth
        shimo = self._js_client.joyspace_post(
            "/v1/sm/getShiMoAuthorityInfo", {"pageId": self._page_id}
        )
        self._shimo_token = shimo.get("data", {}).get("token", "")

        # Step 2: Get snapshotUrl from v2 basic info
        info = self._js_client.joyspace_get(
            f"/v2/pages/{self._page_id}/basic", params={"embedLink": "1"}
        )
        snapshot_url = info.get("data", {}).get("embedLink", {}).get("snapshotUrl", "")
        if not snapshot_url:
            raise RuntimeError(f"Page {self._page_id} has no WPS snapshotUrl (not a WPS sheet)")

        # Parse query params from snapshotUrl
        from urllib.parse import urlparse, parse_qs, urlencode

        parsed = urlparse(snapshot_url)
        qp = parse_qs(parsed.query)
        self._w_signature = qp.get("_w_signature", [""])[0]
        self._w_appid = qp.get("_w_appid", [WPS_APP_ID])[0]
        self._wps_file_id = qp.get("_w_third_file_id", [""])[0]
        w_expire_time = qp.get("_w_expire_time", [""])[0]

        # Step 3: Load WPS page to get csrf_token + cookies
        self._session = requests.Session()
        self._session.cookies.set("sso.jd.com", self._js_client.sso_token, domain=".jd.com")

        self._full_url = snapshot_url + "&" + urlencode({
            "_w_tokentype": "1",
            "lang": "zh-CN",
            "_x_third_u_id": "",
            "_x_third_p_id": f"/sheets/{self._page_id}",
        })

        r = self._session.get(self._full_url, timeout=15)
        r.raise_for_status()
        csrf_match = re.search(r'"csrf_token":"([^"]+)"', r.text)
        self._csrf_token = csrf_match.group(1) if csrf_match else ""

        self._user_query = urlencode({
            "_w_appid": self._w_appid,
            "_w_docs_source": "dc-appfile",
            "_w_expire_time": w_expire_time,
            "_w_third_appid": qp.get("_w_third_appid", [WPS_THIRD_APP_ID])[0],
            "_w_third_file_id": self._wps_file_id,
            "route_key": "",
            "_w_signature": self._w_signature,
        })

        # Step 4: Create WPS editing session
        r = self._session.post(
            f"{WPS_BASE}/weboffice/api/v3/office/session/{self._wps_file_id}/et?first",
            headers={
                "Referer": self._full_url,
                "X-CSRF-Rand": self._csrf_token,
                "X-App-Id": self._w_appid,
                "X-App-Signature": self._w_signature,
                "X-User-Token": self._shimo_token,
                "X-User-Query": self._user_query,
                "Content-Type": "text/plain;charset=UTF-8",
            },
            data=json.dumps({
                "token": self._shimo_token,
                "group": WPS_GROUP,
                "connid": f"wps_core_{self._page_id[:8]}",
                "fileid": "",
                "front_ver": WPS_FRONT_VER,
            }),
            timeout=15,
        )
        r.raise_for_status()
        session_data = r.json()
        self._session_id = session_data.get("sessionId", "")
        self._session_token = session_data.get("token", "")

        self._initialized = True

    def _headers(self) -> dict:
        self._init_auth()
        return {
            "Referer": self._full_url,
            "X-CSRF-Rand": self._csrf_token,
            "X-App-Id": self._w_appid,
            "X-App-Signature": self._w_signature,
            "X-User-Token": self._shimo_token,
            "X-User-Query": self._user_query,
            "X-Session-Id": self._session_id,
            "X-Forward-Region": "",
        }

    def _get(self, path: str, **kwargs) -> dict:
        self._init_auth()
        r = self._session.get(f"{WPS_BASE}{path}", headers=self._headers(), timeout=15, **kwargs)
        r.raise_for_status()
        return r.json()

    def _post(self, path: str, data=None, **kwargs) -> dict:
        self._init_auth()
        headers = {**self._headers(), "Content-Type": "text/plain;charset=UTF-8"}
        r = self._session.post(
            f"{WPS_BASE}{path}", headers=headers,
            data=json.dumps(data) if data else None, timeout=15, **kwargs,
        )
        r.raise_for_status()
        return r.json()

    @property
    def wps_file_id(self) -> str:
        self._init_auth()
        return self._wps_file_id


def _get_wps_client(client: JoySpaceClient, params: dict) -> WPSClient:
    page_id = params.get("page_id") or params.get("pageId", "")
    if not page_id:
        raise ValueError("page_id is required")
    return WPSClient(client, page_id)


def wps_get_file_info(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格文件信息（名称、大小、创建者、权限等）"""
    wps = _get_wps_client(client, params)
    return wps._get(f"/weboffice/api/v3/office/file/{wps.wps_file_id}")


def wps_get_comments(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格评论"""
    wps = _get_wps_client(client, params)
    review_status = params.get("review_status", "1,2")
    return wps._get(
        f"/weboffice/api/v3/office/file/{wps.wps_file_id}/comments/all",
        params={"review_status": review_status},
    )


def wps_get_svg_preview(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格SVG预览渲染"""
    wps = _get_wps_client(client, params)
    sheet_index = params.get("sheet_index", 0)
    wps._init_auth()
    headers = {**wps._headers(), "Content-Type": "text/plain;charset=UTF-8"}
    r = wps._session.post(
        f"{WPS_BASE}/weboffice/api/v3/office/file/{wps.wps_file_id}/svg/et",
        headers=headers,
        data=json.dumps({
            "token": wps._session_token,
            "group": WPS_GROUP,
            "sheet_index": sheet_index,
        }),
        timeout=30,
    )
    r.raise_for_status()
    return {"svg_content": r.text, "content_type": r.headers.get("content-type", "")}


def wps_get_copy_ticket(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格复制票据（用于复制/导出）"""
    wps = _get_wps_client(client, params)
    return wps._get(f"/weboffice/api/v3/office/file/{wps.wps_file_id}/copy/ticket")


def wps_get_env_extra(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格环境配置（附件限制等）"""
    wps = _get_wps_client(client, params)
    return wps._get(f"/weboffice/api/v3/office/file/{wps.wps_file_id}/wpsenv_extra_info")


def wps_get_recover_crypt(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格加密恢复密钥"""
    wps = _get_wps_client(client, params)
    return wps._get(f"/weboffice/api/v3/office/file/{wps.wps_file_id}/recover_crypt")


def wps_get_custom_attribute(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格自定义属性"""
    wps = _get_wps_client(client, params)
    keys = params.get("keys", "")
    namespace = params.get("namespace", "user")
    file_id = params.get("use_full_id", False) and f"{WPS_APP_ID}:{wps.wps_file_id}" or wps.wps_file_id
    return wps._get(
        f"/weboffice/api/v3/office/file/{file_id}/custom/attribute",
        params={"keys": keys, "namespace": namespace},
    )


def wps_get_watermark(client: JoySpaceClient, params: dict) -> dict:
    """获取WPS表格水印配置"""
    wps = _get_wps_client(client, params)
    return wps._get(f"/weboffice/api/v3/office/file/{wps.wps_file_id}/multiwatermark")


def wps_is_wps_sheet(client: JoySpaceClient, params: dict) -> dict:
    """判断一个pageType=18的页面是否为WPS新表格（而非旧ShiMo表格）"""
    page_id = params.get("page_id") or params.get("pageId", "")
    if not page_id:
        raise ValueError("page_id is required")

    # WPS sheets have a snapshotUrl in embedLink
    info = client.joyspace_get(f"/v2/pages/{page_id}/basic", params={"embedLink": "1"})
    snapshot_url = info.get("data", {}).get("embedLink", {}).get("snapshotUrl", "")

    is_wps = "joyspace-office.jd.com" in snapshot_url if snapshot_url else False
    wps_file_id = ""
    if is_wps:
        from urllib.parse import urlparse, parse_qs
        qp = parse_qs(urlparse(snapshot_url).query)
        wps_file_id = qp.get("_w_third_file_id", [""])[0]

    return {
        "page_id": page_id,
        "is_wps_sheet": is_wps,
        "wps_file_id": wps_file_id,
        "snapshot_url": snapshot_url,
    }


def extract_hyperlinks(client: JoySpaceClient, params: dict) -> dict:
    """提取 JoySpace 传统表格(pageType=18)中所有单元格超链接。

    背景：传统表格由 WPS 在线组件渲染在跨域 iframe 里，超链接地址只存在 WPS 数据模型中，
    REST API (sheets.getEtRangeData) 只返回单元格显示文本不返回链接地址。
    本 action 通过 playwright 打开页面、定位 office iframe、调用 WPSOpenApi 读取 Hyperlinks 集合。

    Params:
        page_id (str): 必填，表格页面 ID
        worksheet_id: 可选，WPS Worksheets.Item 的连续 index(1,2,3...)，非 sheetId。
            传 None 遍历所有用户工作表。注意 sheetId 与 index 不一致，建议不传走全表遍历。
        headless (bool): 可选，默认 True（无头浏览器）
    Returns:
        {"status": "success", "page_id":..., "count":N,
         "links":[{"row","col","address","text","worksheet","worksheet_index"},...]}
        失败返回 {"status": "error", "error": "..."}
    依赖：可选依赖 playwright（缺失时返回清晰错误提示而非崩溃）。
    """
    page_id = params.get("page_id") or params.get("pageId", "")
    if not page_id:
        return {"status": "error", "error": "缺少 page_id 参数，请提供表格页面 ID 或链接"}

    headless = params.get("headless", True)
    if isinstance(headless, str):
        headless = headless.lower() in ("true", "1", "yes")

    worksheet_id = params.get("worksheet_id") or params.get("worksheetId")

    # 延迟 import：playwright 是可选依赖
    try:
        from sheet_link_extractor import extract_links_sync
    except ImportError:
        return {
            "status": "error",
            "error": "超链接提取需要 playwright：pip install playwright && playwright install chromium",
        }

    try:
        links = extract_links_sync(client.sso_token, page_id, headless=headless,
                                   worksheet_id=worksheet_id)
    except Exception as e:
        return {"status": "error", "error": f"超链接提取失败: {e}", "page_id": page_id}

    return {
        "status": "success",
        "page_id": page_id,
        "count": len(links),
        "links": links,
    }
