"""
文档管理 actions - 创建/列出/目录/内容读取/删除
"""

import json
import re
import uuid

from .gateway import JoySpaceClient


def _gen_id():
    return uuid.uuid4().hex[:6]


def _normalize_img_url(url: str) -> str:
    """Normalize JoySpace image URLs to the /v1/files/ format.

    JS pages store images as /v1/files/{file_id}/link, but exported markdown
    or page_to_markdown output may use /v2/pages/{page_id}/file/{file_id}/link.
    The /v2/pages/ variant requires the source page context and fails in new pages.
    /v1/files/ works cross-page and is the canonical format from the API.
    """
    m = re.match(
        r'(https?://[^/]+)?/v2/pages/[^/]+/file/([^/]+)/link',
        url,
    )
    if m:
        prefix = m.group(1) or "https://apijoyspace.jd.com"
        file_id = m.group(2)
        return f"{prefix}/v1/files/{file_id}/link"
    return url


def _fix_block_img_urls(blocks: list) -> None:
    """Fix /v2/pages/.../file/ image URLs in a blocks list to /v1/files/ format (in-place)."""
    for block in blocks:
        if not isinstance(block, dict):
            continue
        if block.get("type") == "img" and "url" in block:
            block["url"] = _normalize_img_url(block["url"])
        # Also fix images nested inside table cells, list items, etc.
        for child in block.get("children", []):
            if isinstance(child, dict) and child.get("type") == "img" and "url" in child:
                child["url"] = _normalize_img_url(child["url"])


def _markdown_to_blocks(md: str, title: str = "", *, rich_tables: bool = False,
                         table_style: str = "plain", color_policy: str = "neutral",
                         auto_merge: bool = True, style_overrides: dict | None = None) -> list:
    """将 markdown 字符串转换为 JoySpace block 数组格式

    Args:
        rich_tables: 启用富表格渲染（HTML table 解析 + 自动列宽推断）
        table_style: 表格样式预设（plain/executive-red/success-green/scorecard-gray）
        color_policy: 颜色策略（neutral/red-black-green/green-neutral/red-neutral）
        auto_merge: 自动合并分组空白单元格
        style_overrides: 覆盖表格样式属性，如 {"headerBg": "#F5F5F5", "headerBorder": "#DEE0E3"}
    """
    lines = md.split('\n')
    blocks = []
    i = 0
    # Skip YAML frontmatter (--- ... ---)
    if lines and lines[0].strip() == '---':
        i = 1
        while i < len(lines) and lines[i].strip() != '---':
            i += 1
        i += 1  # skip closing ---
    while i < len(lines):
        line = lines[i]

        if not line.strip():
            i += 1
            continue

        m = re.match(r'^(#{1,6})\s+(.+)$', line)
        if m:
            level = len(m.group(1))
            text = m.group(2)
            if level == 1 and text.strip() == title.strip() and not blocks:
                i += 1
                continue
            font_size = {1: 26, 2: 22, 3: 20, 4: 18, 5: 16, 6: 14}[level]
            blocks.append({
                'type': 'p', 'id': _gen_id(), 'header': level,
                'children': [{'fontSize': font_size, 'text': text}],
            })
            i += 1
            continue

        # Image: ![alt](url)
        m = re.match(r'^!\[([^\]]*)\]\(([^)]+)\)\s*$', line)
        if m:
            img_url = _normalize_img_url(m.group(2))
            blocks.append({'type': 'img', 'id': _gen_id(), 'url': img_url, 'alt': m.group(1), 'children': [{'text': ''}]})
            i += 1
            continue

        # Foldable block: <details><summary>...</summary>
        m = re.match(r'^<details>\s*$', line, re.IGNORECASE)
        if m:
            summary = ""
            inner_blocks = []
            i += 1
            # Read summary
            if i < len(lines):
                sm = re.match(r'^<summary>(.*?)</summary>\s*$', lines[i], re.IGNORECASE)
                if sm:
                    summary = sm.group(1)
                    i += 1
            # Read inner content until </details>
            inner_start = i
            while i < len(lines) and not re.match(r'^</details>\s*$', lines[i], re.IGNORECASE):
                i += 1
            # Parse inner lines recursively
            inner_md = '\n'.join(lines[inner_start:i])
            inner_blocks = _markdown_to_blocks(inner_md, title="")
            fold = {'type': 'foldable-block', 'id': _gen_id(), 'name': summary, 'children': inner_blocks}
            blocks.append(fold)
            i += 1  # skip </details>
            continue

        # HTML table: <table>...</table>
        m = re.match(r'^<table\b', line, re.IGNORECASE)
        if m:
            html_lines = [line]
            i += 1
            while i < len(lines) and not re.search(r'</table>', lines[i], re.IGNORECASE):
                html_lines.append(lines[i])
                i += 1
            if i < len(lines):
                html_lines.append(lines[i])  # include line containing </table>
                i += 1
            from api.rich_table import html_table_to_slate
            table_blocks = html_table_to_slate(
                '\n'.join(html_lines),
                style_preset=table_style,
                color_policy=color_policy,
                auto_merge=auto_merge,
                style_overrides=style_overrides,
            )
            blocks.extend(table_blocks)
            continue

        # List with indent: leading spaces + marker
        m = re.match(r'^(\s*)([-*+])\s+(.+)$', line)
        if m:
            indent = len(m.group(1)) // 2
            blocks.append({'type': 'list', 'id': _gen_id(), 'value': 'bullet', 'indent': indent, 'children': _parse_inline(m.group(3))})
            i += 1
            continue

        m = re.match(r'^(\s*)(\d+)\.\s+(.+)$', line)
        if m:
            indent = len(m.group(1)) // 2
            blocks.append({'type': 'list', 'id': _gen_id(), 'value': 'ordered', 'indent': indent, 'children': _parse_inline(m.group(3))})
            i += 1
            continue

        # Table: | header | ... | followed by | --- | ... |
        m = re.match(r'^\|(.+)\|\s*$', line)
        if m and i + 1 < len(lines) and re.match(r'^\|[\s\-:|]+\|\s*$', lines[i + 1]):
            header_cells = [c.strip() for c in m.group(1).split('|')]
            i += 2  # skip header + separator
            rows = []
            while i < len(lines):
                rm = re.match(r'^\|(.+)\|\s*$', lines[i])
                if not rm:
                    break
                row_cells = [c.strip() for c in rm.group(1).split('|')]
                rows.append(row_cells)
                i += 1
            # Build table block
            if rich_tables:
                from api.rich_table import table_block
                row_descriptors = [[{"text": cell} for cell in row] for row in rows]
                table_meta = {
                    "stylePreset": table_style,
                    "colorPolicy": color_policy,
                    "autoMergeGroupCells": auto_merge,
                    "autoColWidths": True,
                    "fillPageWidth": True,
                }
                if style_overrides:
                    table_meta["style"] = dict(style_overrides)
                table_blocks = table_block(
                    columns=header_cells,
                    rows=row_descriptors,
                    table=table_meta,
                )
                blocks.extend(table_blocks)
            else:
                table_children = []
                # Header row
                header_row = {'type': 'table-row', 'id': _gen_id(), 'children': []}
                for cell_text in header_cells:
                    header_row['children'].append({'type': 'table-cell', 'id': _gen_id(), 'children': _parse_cell_children(cell_text)})
                table_children.append(header_row)
                # Body rows
                for row_cells in rows:
                    row = {'type': 'table-row', 'id': _gen_id(), 'children': []}
                    for cell_text in row_cells:
                        row['children'].append({'type': 'table-cell', 'id': _gen_id(), 'children': _parse_cell_children(cell_text)})
                    table_children.append(row)
                width = len(header_cells)
                blocks.append({'type': 'table', 'id': _gen_id(), 'width': [100] * width, 'children': table_children})
            continue

        m = re.match(r'^>\s*(.*)$', line)
        if m:
            blocks.append({'type': 'block-quote', 'id': _gen_id(), 'children': _parse_inline(m.group(1))})
            i += 1
            continue

        # Divider: ---
        if re.match(r'^-{3,}\s*$', line):
            blocks.append({'type': 'divider', 'id': _gen_id(), 'children': [{'text': ''}]})
            i += 1
            continue

        if line.strip().startswith('```'):
            lang = line.strip()[3:].strip()
            code_lines = []
            i += 1
            while i < len(lines) and not lines[i].strip().startswith('```'):
                code_lines.append(lines[i])
                i += 1
            i += 1
            blocks.append({
                'type': 'block-code', 'id': _gen_id(), 'lang': lang,
                'children': [{'type': 'block-code-line', 'id': _gen_id(), 'children': [{'text': cl}]} for cl in code_lines]
            })
            continue

        blocks.append({'type': 'p', 'id': _gen_id(), 'children': _parse_inline(line)})
        i += 1

    return blocks


def _parse_inline(text: str) -> list:
    """解析行内格式（加粗、斜体、链接）"""
    parts = []
    remaining = text
    while remaining:
        # Inline link: [text](url)
        m = re.search(r'\[([^\]]+)\]\(([^)]+)\)', remaining)
        if m and (not remaining[:m.start()].rstrip().endswith('!')):
            before = remaining[:m.start()]
            if before:
                parts.extend(_parse_inline_simple(before))
            parts.append({'type': 'link', 'id': _gen_id(), 'url': m.group(2),
                          'children': [{'text': m.group(1)}]})
            remaining = remaining[m.end():]
            continue
        # Bold: **text**
        m = re.search(r'\*\*(.+?)\*\*', remaining)
        if m:
            before = remaining[:m.start()]
            if before:
                parts.extend(_parse_inline_simple(before))
            parts.append({'text': m.group(1), 'bold': True})
            remaining = remaining[m.end():]
            continue
        # Italic: *text*
        m = re.search(r'\*(.+?)\*', remaining)
        if m:
            before = remaining[:m.start()]
            if before:
                parts.extend(_parse_inline_simple(before))
            parts.append({'text': m.group(1), 'italic': True})
            remaining = remaining[m.end():]
            continue
        parts.append({'text': remaining})
        break
    return parts or [{'text': text}]


def _parse_cell_children(cell_text: str) -> list:
    """Parse table cell content — images become direct children of table-cell."""
    cell_text = cell_text.strip()
    # Pure image cell: ![alt](url)
    m = re.match(r'^!\[([^\]]*)\]\(([^)]+)\)\s*$', cell_text)
    if m:
        return [{'type': 'img', 'id': _gen_id(), 'url': m.group(2), 'alt': m.group(1), 'children': [{'text': ''}]}]
    return [{'type': 'p', 'id': _gen_id(), 'children': _parse_inline(cell_text)}]


def _parse_inline_simple(text: str) -> list:
    """Parse inline without links (for inside link prefix context)."""
    parts = []
    remaining = text
    while remaining:
        m = re.search(r'\*\*(.+?)\*\*', remaining)
        if m:
            before = remaining[:m.start()]
            if before:
                parts.append({'text': before})
            parts.append({'text': m.group(1), 'bold': True})
            remaining = remaining[m.end():]
        else:
            parts.append({'text': remaining})
            break
    return parts


# ─── Page width detection ───

# 标宽页面内容区宽度约 960px，超宽页面约 1600px
# 实际表格可用宽度需扣除左侧目录导航(~220px)和两侧留白(~30px)
STANDARD_PAGE_CONTENT_WIDTH = 960
ULTRAWIDE_PAGE_CONTENT_WIDTH = 1600
ULTRAWIDE_TABLE_AVAILABLE_WIDTH = 1360  # 1600 - 220(目录) - 20(左留白)


def _detect_page_width_mode(content) -> str:
    """基于文档内容自动判断应使用标宽页面("0")还是超宽页面("1")。

    判断依据：
    1. 任意表格列数 >= 7 → 超宽
    2. 任意表格内容估算宽度 > 960px → 超宽
    3. 多个表格且平均列数 >= 5 → 超宽
    4. 含 HTML table 且 colSpan 合并后宽度 >= 7 → 超宽
    5. 其余 → 标宽

    Args:
        content: markdown 字符串或 Slate blocks 列表

    Returns:
        "0" (标宽) 或 "1" (超宽)
    """
    if isinstance(content, str):
        return _detect_width_from_markdown(content)
    elif isinstance(content, list):
        return _detect_width_from_blocks(content)
    return "0"


def _detect_width_from_markdown(md: str) -> str:
    """从 markdown 内容判断页面宽度。"""
    lines = md.split('\n')
    max_table_cols = 0
    table_count = 0
    total_cols = 0
    has_wide_html_table = False

    i = 0
    while i < len(lines):
        line = lines[i]

        # Markdown table: | header | ... |
        m = re.match(r'^\|(.+)\|\s*$', line)
        if m and i + 1 < len(lines) and re.match(r'^\|[\s\-:|]+\|\s*$', lines[i + 1]):
            cols = [c.strip() for c in m.group(1).split('|')]
            col_count = len(cols)
            max_table_cols = max(max_table_cols, col_count)
            total_cols += col_count
            table_count += 1
            i += 2
            while i < len(lines) and re.match(r'^\|(.+)\|\s*$', lines[i]):
                i += 1
            continue

        # HTML table: check for colspan
        if re.match(r'^<table\b', line, re.IGNORECASE):
            html_lines = [line]
            i += 1
            while i < len(lines) and not re.match(r'^</table>\s*$', lines[i], re.IGNORECASE):
                html_lines.append(lines[i])
                i += 1
            if i < len(lines):
                html_lines.append(lines[i])
                i += 1
            html_text = '\n'.join(html_lines)
            # Count max colspan sum in a row
            for row_match in re.finditer(r'<tr\b.*?</tr>', html_text, re.IGNORECASE | re.DOTALL):
                row_cols = 0
                for cell_match in re.finditer(r'<(td|th)\b[^>]*?>', row_match.group(0), re.IGNORECASE):
                    colspan_m = re.search(r'colspan\s*=\s*["\']?(\d+)', cell_match.group(0), re.IGNORECASE)
                    row_cols += int(colspan_m.group(1)) if colspan_m else 1
                max_table_cols = max(max_table_cols, row_cols)
            table_count += 1
            total_cols += max_table_cols
            continue

        i += 1

    # Decision rules
    if max_table_cols >= 7:
        return "1"
    # Estimate content width: assume ~100px per column for narrow tables, ~130px for wider
    est_width = max_table_cols * (130 if max_table_cols >= 5 else 100)
    if est_width > STANDARD_PAGE_CONTENT_WIDTH:
        return "1"
    if table_count >= 2 and (total_cols / table_count) >= 5:
        return "1"
    return "0"


def _detect_width_from_blocks(blocks: list) -> str:
    """从 Slate blocks 判断页面宽度。"""
    max_table_cols = 0
    table_count = 0
    total_cols = 0

    for block in blocks:
        if not isinstance(block, dict) or block.get("type") != "table":
            continue
        table_rows = block.get("children", [])
        for row in table_rows:
            if not isinstance(row, dict) or row.get("type") != "table-row":
                continue
            visible_cols = sum(
                1 for c in row.get("children", [])
                if isinstance(c, dict) and c.get("type") == "table-cell" and not c.get("hidden")
            )
            # Account for colSpan
            span_cols = 0
            for c in row.get("children", []):
                if isinstance(c, dict) and c.get("type") == "table-cell" and not c.get("hidden"):
                    span_cols += int(c.get("colSpan", 1) or 1)
            max_table_cols = max(max_table_cols, span_cols or visible_cols)
        if max_table_cols > 0:
            table_count += 1
            total_cols += max_table_cols

    if max_table_cols >= 7:
        return "1"
    if max_table_cols * 130 > STANDARD_PAGE_CONTENT_WIDTH:
        return "1"
    if table_count >= 2 and (total_cols / table_count) >= 5:
        return "1"
    return "0"


JOYSPACE_LINK_PATTERN = re.compile(
    r'https?://joyspace\.jd\.com/(pages|sheets|table|doc|h/personal/documents)/([A-Za-z0-9_-]+)'
)


def extract_page_id(url_or_id: str) -> str:
    match = JOYSPACE_LINK_PATTERN.search(url_or_id)
    if match:
        return match.group(2)
    if re.match(r'^[A-Za-z0-9_-]+$', url_or_id):
        return url_or_id
    raise ValueError(f"无法从输入中提取 page_id: {url_or_id}")


def _cleanup_default_aitable_records(client: JoySpaceClient, page_id: str):
    """创建多维表后清理模板自带的空记录"""
    import time
    from . import aitable
    time.sleep(2)
    try:
        schema = aitable.get_schema(client, {"page_id": page_id})
        if schema.get("code") != 0:
            return
        sheets = schema.get("data", {}).get("sheets", [])
        if not sheets:
            return
        sheet_id = sheets[0]["id"]
        result = aitable.list_records_by_page(client, {
            "page_id": page_id, "sheet_id": sheet_id,
            "page_num": 1, "page_size": 50,
        })
        records = result.get("data", {}).get("records", [])
        empty_ids = [r["id"] for r in records if r.get("fields") in ("{}", "", None, {})]
        if empty_ids:
            aitable.delete_records(client, {
                "page_id": page_id, "sheet_id": sheet_id, "record_ids": empty_ids,
            })
    except Exception:
        pass


def create_doc_routing(client: JoySpaceClient, params: dict) -> dict:
    data = {
        "title": params.get("title", ""),
        "team_id": params.get("team_id", "root"),
        "folder_id": params.get("folder_id", "root"),
    }
    if params.get("content") is not None:
        data["content"] = params["content"]
    if params.get("doc_type"):
        data["doc_type"] = params["doc_type"]
    if params.get("page_type"):
        data["page_type"] = params["page_type"]
    if params.get("template_id"):
        data["template_id"] = params["template_id"]

    doc_type = data.get("doc_type", "")
    page_type = data.get("page_type")

    type_to_page_type = {
        "document": 13, "doc": 13, "wiki": 13,
        "sheets": 18, "sheet": 18, "spreadsheet": 18,
        "table": 21, "aitable": 21,
        "ppt": 19, "presentation": 19, "slides": 19,
        "board": 25, "whiteboard": 25,
        "mind": 16, "mindmap": 16, "mind_map": 16,
        "meeting": 15,
    }

    if doc_type in type_to_page_type:
        page_type = type_to_page_type[doc_type]
    elif page_type is None:
        page_type = 13

    if page_type in (18, 21, 19):
        # sheets(18), aitable/table(21), PPT(19) must use /v2/pages
        payload = {
            "title": data["title"],
            "pageType": page_type,
            "teamId": data["team_id"],
            "folderId": data["folder_id"],
        }
        result = client.joyspace_post("/v2/pages", payload)
        if page_type == 21 and result.get("status") == "success":
            _cleanup_default_aitable_records(client, result["data"]["id"])
        return result
    elif page_type == 13:
        payload = {
            "title": data["title"],
            "pageType": 13,
            "teamId": data["team_id"],
            "folderId": data["folder_id"],
        }
        content = data.get("content")
        if content is not None:
            # Unwrap PowerShell Get-Content wrapper (dict with 'value' + PS* metadata)
            if isinstance(content, dict) and "value" in content and "PSPath" in content:
                content = str(content["value"])
            if isinstance(content, str):
                content = _markdown_to_blocks(content, title=data["title"])
            elif not isinstance(content, list):
                return {"status": "error", "error": f"content 参数类型错误: 期望 str 或 list，收到 {type(content).__name__}。如传入 markdown 文本请确保为字符串类型。"}
            if isinstance(content, list):
                if len(content) == 0:
                    return {"status": "error", "error": "content 为空列表，将导致创建空文档。请确认源页面有内容，或传入非空 content 参数。", "hint": "如果是通过 page_to_markdown 获取 blocks，请检查源页面是否为空；如果是 markdown 转换，请确认 markdown 内容非空。"}
                _fix_block_img_urls(content)
            payload["content"] = content
        if data.get("template_id"):
            payload["templateId"] = data["template_id"]
        result = client.joyspace_post("/v1/pages", payload)
        # Post-create: auto-detect and set page width (标宽/超宽)
        page_id = (result.get("data") or {}).get("id") if result.get("status") == "success" else None
        if page_id:
            # Determine page width mode
            adaptive_layout_param = params.get("adaptive_layout")
            if adaptive_layout_param is not None:
                # User explicitly specified
                layout_value = adaptive_layout_param if isinstance(adaptive_layout_param, str) else ("1" if adaptive_layout_param else "0")
            elif params.get("auto_page_width", True) and content:
                # Auto-detect from content
                layout_value = _detect_page_width_mode(content)
            else:
                layout_value = None

            if layout_value is not None:
                try:
                    client.joyspace_post(
                        f"/v1/pages/{page_id}/settings",
                        {"adaptiveLayout": layout_value},
                    )
                    result["_pageWidth"] = "ultrawide" if layout_value == "1" else "standard"
                except Exception:
                    pass

            # Post-create verification: read back content to check integrity
            if content:
                import time
                time.sleep(2)
                try:
                    verify_result = get_normal_json_content(client, {"page_id": page_id})
                    verify_content = (verify_result.get("data") or {}).get("content") or []
                    if isinstance(verify_content, list):
                        expected_blocks = content if isinstance(content, list) else _markdown_to_blocks(str(content), title=data["title"])
                        block_count_delta = len(expected_blocks) - len(verify_content)
                        result["_verification"] = {
                            "expected_blocks": len(expected_blocks),
                            "actual_blocks": len(verify_content),
                            "block_count_delta": block_count_delta,
                            "content_loss": block_count_delta > 2,
                        }
                        if block_count_delta > len(expected_blocks) * 0.3:
                            result["_verification"]["warning"] = f"创建后内容块数量严重不足：期望 {len(expected_blocks)} 个，实际 {len(verify_content)} 个，损失率 {block_count_delta/len(expected_blocks)*100:.0f}%"
                except Exception:
                    pass
        return result
    else:
        # meeting(15), mind(16), board(25), doc(17) etc.
        payload = {
            "title": data["title"],
            "pageType": page_type,
            "teamId": data["team_id"],
            "folderId": data["folder_id"],
        }
        return client.joyspace_post("/v2/pages", payload)


def create_doc_rich(client: JoySpaceClient, params: dict) -> dict:
    """Create a JoySpace document with rich table rendering.

    Supports HTML <table> blocks (colspan/rowspan), auto column width inference,
    and styled table rendering. Accepts the same params as create_doc_routing plus:

    - table_style: override style preset (plain/executive-red/success-green/scorecard-gray)
    - color_policy: override color policy (neutral/red-black-green/green-neutral/red-neutral)
    - auto_merge: auto-merge blank group cells in tables (default True)
    - adaptive_layout: "0"=标宽页面, "1"=超宽页面, True=auto-detect (default True)
    - auto_page_width: auto-detect 标宽/超宽 from content (default True)
    - style_overrides: dict to override table style attributes, e.g.
        {"headerBg": "#F5F5F5", "headerBorder": "#DEE0E3", "bodyBorder": "#DEE0E3",
         "headerFontColor": "#1F2328"}
    """
    data = {
        "title": params.get("title", ""),
        "team_id": params.get("team_id", "root"),
        "folder_id": params.get("folder_id", "root"),
    }
    table_style = params.get("table_style", "plain")
    color_policy = params.get("color_policy", "neutral")
    auto_merge = params.get("auto_merge", True)
    adaptive_layout = params.get("adaptive_layout", True)
    style_overrides = params.get("style_overrides")

    content = None
    if params.get("content"):
        content = params["content"]
        # Unwrap PowerShell Get-Content wrapper (dict with 'value' + PS* metadata)
        if isinstance(content, dict) and "value" in content and "PSPath" in content:
            content = str(content["value"])
        if isinstance(content, str):
            content = _markdown_to_blocks(
                content,
                title=data["title"],
                rich_tables=True,
                table_style=table_style,
                color_policy=color_policy,
                auto_merge=auto_merge,
                style_overrides=style_overrides,
            )
        elif not isinstance(content, list):
            return {"status": "error", "error": f"content 参数类型错误: 期望 str 或 list，收到 {type(content).__name__}。如传入 markdown 文本请确保为字符串类型。"}
        if isinstance(content, list):
            _fix_block_img_urls(content)
        data["content"] = content

    payload = {
        "title": data["title"],
        "pageType": 13,
        "teamId": data["team_id"],
        "folderId": data["folder_id"],
    }
    if data.get("content"):
        payload["content"] = data["content"]
    if params.get("template_id"):
        payload["templateId"] = params["template_id"]

    result = client.joyspace_post("/v1/pages", payload)

    page_id = (result.get("data") or {}).get("id") if result.get("status") == "success" else None
    if page_id:
        # Determine page width mode
        if isinstance(adaptive_layout, str):
            layout_value = adaptive_layout
        elif params.get("auto_page_width", True) and content:
            layout_value = _detect_page_width_mode(content)
        elif adaptive_layout:
            layout_value = "1"
        else:
            layout_value = "0"

        try:
            client.joyspace_post(
                f"/v1/pages/{page_id}/settings",
                {"adaptiveLayout": layout_value},
            )
            result["_pageWidth"] = "ultrawide" if layout_value == "1" else "standard"
        except Exception:
            pass

    return result


def apply_batch_styles(client: JoySpaceClient, params: dict) -> dict:
    """批量设置文档中表格的样式（颜色、加粗等）。

    两种使用模式：
    1. 从已有页面提取并重新发布（source_page_id）
    2. 直接对传入的 blocks 应用样式后创建新文档（blocks）

    Params:
        source_page_id (str): 源页面 ID（可选，与 blocks 二选一）
        blocks (list): Slate blocks 数组（可选，与 source_page_id 二选一）
        title (str): 新文档标题
        team_id (str): 团队 ID
        folder_id (str): 文件夹 ID
        table_header_bg (str): 表头背景色，默认 "#F2F2F2"（浅灰色）。如 "#FEF3F3"
        table_header_font_color (str): 表头字体色，如 "#1F2328"
        table_header_bold (bool): 表头是否加粗，默认 True
        table_body_bold (bool): 表格内容是否加粗
        row_styles (dict): 指定行的样式，key为行索引，value为样式dict。
            如 {"0": {"bgColor": "#F8FAFC", "bold": True}, "3": {"fontColor": "#D92D20"}}
        col_styles (dict): 指定列的样式，key为列索引，value为样式dict。
            如 {"0": {"bgColor": "#F5F5F5"}, "2": {"bold": True, "fontColor": "#2EA121"}}
        cell_styles (list): 指定单元格的样式列表，每项为 {"row": 0, "col": 1, "bgColor": "...", ...}
        global_bold (bool): 全局加粗所有文字
        global_font_color (str): 全局字体颜色
    """
    import copy

    # Get blocks from source page or params
    source_page_id = params.get("source_page_id")
    blocks = params.get("blocks")

    if source_page_id:
        content_result = get_normal_json_content(client, {"page_id": source_page_id})
        content = (content_result.get("data") or {}).get("content") or []
        if isinstance(content, str):
            content = json.loads(content)
        if not content:
            return {"status": "error", "error": f"源页面 {source_page_id} 内容为空"}
        import uuid as _uuid
        blocks = copy.deepcopy(content)
        for b in blocks:
            if isinstance(b, dict) and "id" in b:
                b["id"] = _uuid.uuid4().hex[:8]
            for child in b.get("children", []):
                if isinstance(child, dict) and "id" in child:
                    child["id"] = _uuid.uuid4().hex[:8]
    elif not blocks:
        return {"status": "error", "error": "必须提供 source_page_id 或 blocks 参数"}

    # Apply batch styles to blocks
    table_header_bg = params.get("table_header_bg", "#F2F2F2")
    table_header_font_color = params.get("table_header_font_color")
    table_header_bold = params.get("table_header_bold", True)
    table_body_bold = params.get("table_body_bold")
    row_styles = params.get("row_styles", {})
    col_styles = params.get("col_styles", {})
    cell_styles = params.get("cell_styles", [])
    global_bold = params.get("global_bold")
    global_font_color = params.get("global_font_color")

    # Build cell_styles lookup: (row_idx, col_idx) -> style_dict
    cell_style_map = {}
    for cs in cell_styles:
        key = (cs.get("row", -1), cs.get("col", -1))
        cell_style_map[key] = {k: v for k, v in cs.items() if k not in ("row", "col")}

    def _apply_text_style(children, bold=None, font_color=None):
        """Apply style to text leaves in children list."""
        for child in children:
            if isinstance(child, dict):
                if "text" in child and not child.get("type"):
                    if bold is not None:
                        child["bold"] = bold
                    if font_color:
                        child["fontColor"] = font_color
                inner = child.get("children", [])
                if isinstance(inner, list):
                    _apply_text_style(inner, bold, font_color)

    def _apply_cell_style(cell_node, style):
        """Apply style dict to a table-cell node."""
        for key, value in style.items():
            if key in ("bgColor", "borderColor"):
                cell_node[key] = value
            elif key == "bold":
                _apply_text_style(cell_node.get("children", []), bold=value)
            elif key == "fontColor":
                _apply_text_style(cell_node.get("children", []), font_color=value)

    # Process each block
    for block in blocks:
        if not isinstance(block, dict):
            continue

        # Global styles on all text blocks
        if global_bold or global_font_color:
            btype = block.get("type", "")
            if btype in ("p", "list", "block-quote", "foldable-block", "highlight-block"):
                _apply_text_style(
                    block.get("children", []),
                    bold=global_bold,
                    font_color=global_font_color,
                )

        # Table-specific styles
        if block.get("type") == "table":
            table_rows = block.get("children", [])
            for row_idx, table_row in enumerate(table_rows):
                if not isinstance(table_row, dict) or table_row.get("type") != "table-row":
                    continue
                cells = table_row.get("children", [])
                is_header_row = row_idx == 0

                for col_idx, cell_node in enumerate(cells):
                    if not isinstance(cell_node, dict) or cell_node.get("type") != "table-cell":
                        continue

                    # Table header styles
                    if is_header_row:
                        if table_header_bg:
                            cell_node["bgColor"] = table_header_bg
                        if table_header_font_color:
                            _apply_text_style(cell_node.get("children", []), font_color=table_header_font_color)
                        if table_header_bold is not None:
                            _apply_text_style(cell_node.get("children", []), bold=table_header_bold)

                    # Table body bold
                    if not is_header_row and table_body_bold is not None:
                        _apply_text_style(cell_node.get("children", []), bold=table_body_bold)

                    # Row styles
                    row_key = str(row_idx)
                    if row_key in row_styles:
                        _apply_cell_style(cell_node, row_styles[row_key])

                    # Column styles
                    col_key = str(col_idx)
                    if col_key in col_styles:
                        _apply_cell_style(cell_node, col_styles[col_key])

                    # Cell-specific styles
                    cell_key = (row_idx, col_idx)
                    if cell_key in cell_style_map:
                        _apply_cell_style(cell_node, cell_style_map[cell_key])

    # Create new document with styled blocks
    title = params.get("title", "样式文档")
    create_params = {
        "title": title,
        "content": blocks,
        "team_id": params.get("team_id", "root"),
        "folder_id": params.get("folder_id", "root"),
    }
    return create_doc_routing(client, create_params)


def auto_layout_tables(client: JoySpaceClient, params: dict) -> dict:
    """批量优化文档中所有表格的宽度和对齐。

    从已有页面提取 blocks，对所有表格块自动应用：
    1. 内容驱动列宽（表格用多少宽度就用多少，小表格不强制铺满）
    2. 基于列角色的智能对齐（维度列左对齐、指标列右对齐、状态列居中）
    3. 垂直居中（verticalAlign: middle）
    4. 表头居中对齐

    宽度策略：
    - 超宽表格（>页面宽度）→ 按比例缩小到页面宽度
    - 适中表格（>60%页面宽度）→ 拉伸填满页面
    - 小表格 → 保持自然内容宽度，不强制铺满

    两种使用模式：
    1. 从已有页面提取并优化（source_page_id）
    2. 直接对传入的 blocks 优化后创建新文档（blocks）

    Params:
        source_page_id (str): 源页面 ID（可选，与 blocks 二选一）
        blocks (list): Slate blocks 数组（可选，与 source_page_id 二选一）
        title (str): 新文档标题
        team_id (str): 团队 ID
        folder_id (str): 文件夹 ID
        page_width (int): 页面宽度，默认根据页面模式自动检测
        header_align (str): 表头对齐方式，默认 "center"
        body_vertical_align (str): 单元格垂直对齐，默认 "middle"
        fill_page_width (bool): 适中表格是否铺满页面宽度，默认 True
    """
    import copy
    from api.rich_table import (
        _infer_col_widths,
        _column_roles_for_body,
        _column_alignment_labels,
        classify_column,
        normalize_display_text,
        longest_display_units,
        new_id,
        p as p_node,
    )
    from utils.column_roles import display_units

    # Get blocks from source page or params
    source_page_id = params.get("source_page_id")
    blocks = params.get("blocks")

    if source_page_id:
        content_result = get_normal_json_content(client, {"page_id": source_page_id})
        content = (content_result.get("data") or {}).get("content") or []
        if isinstance(content, str):
            content = json.loads(content)
        if not content:
            return {"status": "error", "error": f"源页面 {source_page_id} 内容为空"}
        import uuid as _uuid
        blocks = copy.deepcopy(content)
        for b in blocks:
            if isinstance(b, dict) and "id" in b:
                b["id"] = _uuid.uuid4().hex[:8]
            for child in b.get("children", []):
                if isinstance(child, dict) and "id" in child:
                    child["id"] = _uuid.uuid4().hex[:8]
    elif not blocks:
        return {"status": "error", "error": "必须提供 source_page_id 或 blocks 参数"}

    header_align = params.get("header_align", "center")
    body_valign = params.get("body_vertical_align", "middle")
    fill_page_width = params.get("fill_page_width", True)
    default_page_width = params.get("page_width")
    auto_page_width = params.get("auto_page_width", True)

    # Auto-detect page width mode from blocks
    page_width_mode = None
    if auto_page_width:
        page_width_mode = _detect_width_from_blocks(blocks)

    # Page content width depends on page mode: 标宽=960, 超宽=1360(扣除目录和留白)
    if default_page_width:
        effective_page_width = default_page_width
    elif page_width_mode == "1":
        effective_page_width = ULTRAWIDE_TABLE_AVAILABLE_WIDTH
    else:
        effective_page_width = STANDARD_PAGE_CONTENT_WIDTH

    tables_optimized = 0

    for block in blocks:
        if not isinstance(block, dict) or block.get("type") != "table":
            continue

        table_rows = block.get("children", [])
        if not table_rows:
            continue

        # Determine table width (number of visible columns)
        col_count = 0
        for row in table_rows:
            if not isinstance(row, dict) or row.get("type") != "table-row":
                continue
            visible = sum(1 for c in row.get("children", []) if isinstance(c, dict) and c.get("type") == "table-cell" and not c.get("hidden"))
            col_count = max(col_count, visible)
            break

        if col_count == 0:
            continue

        # ─── Step 1: Infer column widths ───
        # Collect text samples per column for width inference
        col_samples = [[] for _ in range(col_count)]
        col_labels = [""] * col_count

        for row_idx, table_row in enumerate(table_rows):
            if not isinstance(table_row, dict) or table_row.get("type") != "table-row":
                continue
            cells = [c for c in table_row.get("children", []) if isinstance(c, dict) and c.get("type") == "table-cell" and not c.get("hidden")]
            for col_idx, cell_node in enumerate(cells):
                if col_idx >= col_count:
                    break
                # Extract text from cell
                cell_text = _extract_cell_text(cell_node)
                if row_idx == 0:
                    col_labels[col_idx] = cell_text.strip()
                col_samples[col_idx].append(cell_text.strip())

        # Calculate per-column preferred width based on content
        col_widths = []
        page_w = effective_page_width

        for col_idx in range(col_count):
            label = col_labels[col_idx]
            samples = col_samples[col_idx]
            max_w = max((estimated_col_width(label, s)) for s in samples) if samples else 80
            max_w = max(max_w, estimated_col_width(label, label))
            col_widths.append(max_w)

        # Width strategy: use content-based widths, cap at page_w.
        # Tables should NOT be stretched to fill the page — content determines width.
        # Only if the table exceeds page_w do we proportionally shrink.
        min_col_w = 56
        current_total = sum(col_widths)

        if current_total > page_w:
            # Table too wide — proportionally shrink to fit
            scale = page_w / current_total
            col_widths = [max(min_col_w, int(round(w * scale))) for w in col_widths]
            # Fix rounding
            diff = page_w - sum(col_widths)
            if diff != 0:
                sorted_indices = sorted(range(len(col_widths)), key=lambda i: col_widths[i], reverse=True)
                for i in range(abs(diff)):
                    idx = sorted_indices[i % len(sorted_indices)]
                    col_widths[idx] += 1 if diff > 0 else -1
                    if col_widths[idx] < min_col_w:
                        col_widths[idx] = min_col_w
        elif fill_page_width and current_total > page_w * 0.6:
            # Table is reasonably wide (>60% of page) — stretch to fill
            scale = page_w / current_total
            col_widths = [max(min_col_w, int(round(w * scale))) for w in col_widths]
            diff = page_w - sum(col_widths)
            if diff != 0:
                sorted_indices = sorted(range(len(col_widths)), key=lambda i: col_widths[i], reverse=True)
                for i in range(abs(diff)):
                    idx = sorted_indices[i % len(sorted_indices)]
                    col_widths[idx] += 1 if diff > 0 else -1
                    if col_widths[idx] < min_col_w:
                        col_widths[idx] = min_col_w
        # else: keep natural content-based widths (small tables stay small)

        block["colWidths"] = col_widths
        block["width"] = col_widths

        # ─── Step 2: Apply alignment based on column roles ───
        # Classify each column
        col_roles = []
        for col_idx in range(col_count):
            label = col_labels[col_idx]
            samples = col_samples[col_idx]
            role_result = classify_column(label, samples, col_count)
            col_roles.append(role_result.role)

        # Apply alignment to each cell
        for row_idx, table_row in enumerate(table_rows):
            if not isinstance(table_row, dict) or table_row.get("type") != "table-row":
                continue
            cells = [c for c in table_row.get("children", []) if isinstance(c, dict) and c.get("type") == "table-cell" and not c.get("hidden")]
            is_header = (row_idx == 0)

            for col_idx, cell_node in enumerate(cells):
                if col_idx >= len(col_roles):
                    break

                # Vertical alignment
                cell_node["verticalAlign"] = body_valign

                # Horizontal alignment on inner p nodes
                role = col_roles[col_idx]
                if is_header:
                    target_align = header_align
                else:
                    target_align = _role_to_align(role)

                if target_align:
                    _set_cell_text_align(cell_node, target_align)

        tables_optimized += 1

    # Create new document with optimized blocks
    title = params.get("title", "排版优化版")
    create_params = {
        "title": title,
        "content": blocks,
        "team_id": params.get("team_id", "root"),
        "folder_id": params.get("folder_id", "root"),
    }
    # Pass page width mode to create_doc_routing
    if page_width_mode:
        create_params["adaptive_layout"] = page_width_mode
    elif params.get("adaptive_layout"):
        create_params["adaptive_layout"] = params["adaptive_layout"]
    result = create_doc_routing(client, create_params)
    result["_tables_optimized"] = tables_optimized
    result["_pageWidth"] = "ultrawide" if page_width_mode == "1" else "standard"
    return result


def _extract_cell_text(cell_node: dict) -> str:
    """Extract plain text from a table-cell node."""
    parts = []
    for child in cell_node.get("children", []):
        if not isinstance(child, dict):
            continue
        if "text" in child and not child.get("type"):
            parts.append(str(child["text"]))
        elif child.get("type") == "p":
            for sub in child.get("children", []):
                if isinstance(sub, dict):
                    if "text" in sub:
                        parts.append(str(sub["text"]))
                    else:
                        parts.append(_extract_cell_text(sub))
        elif child.get("type") in ("link", "docfile"):
            for sub in child.get("children", []):
                if isinstance(sub, dict) and "text" in sub:
                    parts.append(str(sub["text"]))
    return " ".join(parts).strip()


def estimated_col_width(label: str, *samples: str) -> int:
    """Estimate pixel width for a column based on label and sample content."""
    from utils.column_roles import estimated_text_width
    all_texts = [label] + [s for s in samples if s.strip()]
    if not all_texts:
        return 80
    widths = [estimated_text_width(t) for t in all_texts if t.strip()]
    if not widths:
        return 80
    # Use P90 of content widths as preferred
    widths.sort()
    p90_idx = int(len(widths) * 0.9)
    return max(56, min(widths[p90_idx], 600))


def _role_to_align(role: str) -> str | None:
    """Map column role to horizontal alignment."""
    if role in ("metric", "mixed-value"):
        return "right"
    if role in ("status", "rank", "date"):
        return "center"
    # dimension, name, long-text → left (default, no explicit align)
    return None


def _set_cell_text_align(cell_node: dict, align: str):
    """Set text alignment on all paragraph children of a table-cell."""
    for child in cell_node.get("children", []):
        if isinstance(child, dict):
            if child.get("type") == "p":
                child["align"] = align
            elif child.get("type") == "list":
                # Lists inside cells: set align on inner paragraphs
                for sub in child.get("children", []):
                    if isinstance(sub, dict) and sub.get("type") == "p":
                        sub["align"] = align
            # For status-light or other compound children, set align on the containing p
            inner_children = child.get("children", [])
            if isinstance(inner_children, list):
                for sub in inner_children:
                    if isinstance(sub, dict) and sub.get("type") == "p" and not sub.get("align"):
                        sub["align"] = align


def verify_content_integrity(client: JoySpaceClient, params: dict) -> dict:
    """质检动作：对比源内容与实际内容，检测损失。

    在文档导入、写入、发布等操作后调用，验证内容是否完整。

    Params:
        source_page_id (str): 源页面 ID（与 source_blocks 二选一）
        source_blocks (list): 源 Slate blocks 数组（与 source_page_id 二选一）
        target_page_id (str): 目标页面 ID（必填，要验证的页面）
        check_types (list): 检查类型列表，默认全部。
            可选: "block_count", "text_content", "table_structure", "formatting", "images"
        auto_fix (bool): 是否自动尝试修复（默认 False）
        fix_page_id (str): 修复时使用的页面 ID（默认与 target_page_id 相同）

    Returns:
        dict with keys:
            status: "pass" | "warn" | "fail"
            checks: 各检查项的结果列表
            losses: 检测到的内容损失列表
            fix_applied: 如果 auto_fix=True，记录已应用的修复
    """
    import time

    target_page_id = params.get("target_page_id")
    if not target_page_id:
        return {"status": "error", "error": "必须提供 target_page_id 参数"}

    # Get source content
    source_page_id = params.get("source_page_id")
    source_blocks = params.get("source_blocks")

    if source_page_id:
        src_result = get_normal_json_content(client, {"page_id": source_page_id})
        source_blocks = (src_result.get("data") or {}).get("content") or []
        if isinstance(source_blocks, str):
            source_blocks = json.loads(source_blocks)
    elif not source_blocks:
        return {"status": "error", "error": "必须提供 source_page_id 或 source_blocks 参数"}

    # Get target content
    time.sleep(2)  # Wait for write to propagate
    tgt_result = get_normal_json_content(client, {"page_id": target_page_id})
    target_blocks = (tgt_result.get("data") or {}).get("content") or []
    if isinstance(target_blocks, str):
        target_blocks = json.loads(target_blocks)

    check_types = params.get("check_types", ["block_count", "text_content", "table_structure", "formatting", "images"])
    auto_fix = params.get("auto_fix", False)

    checks = []
    losses = []
    overall_status = "pass"

    # ─── Check 1: Block count ───
    if "block_count" in check_types:
        src_count = len(source_blocks)
        tgt_count = len(target_blocks)
        delta = src_count - tgt_count
        loss_pct = delta / max(src_count, 1) * 100
        check = {
            "type": "block_count",
            "source_count": src_count,
            "target_count": tgt_count,
            "delta": delta,
            "loss_pct": round(loss_pct, 1),
        }
        if delta <= 0:
            check["status"] = "pass"
        elif loss_pct <= 10:
            check["status"] = "warn"
            overall_status = "warn" if overall_status == "pass" else overall_status
        else:
            check["status"] = "fail"
            overall_status = "fail"
        checks.append(check)
        if delta > 0:
            losses.append({"type": "missing_blocks", "count": delta, "loss_pct": round(loss_pct, 1)})

    # ─── Helper: extract text from blocks ───
    def _extract_text(blocks):
        texts = []
        for blk in blocks:
            if not isinstance(blk, dict):
                continue
            btype = blk.get("type", "")
            if btype in ("p", "list", "block-quote"):
                for child in blk.get("children", []):
                    if isinstance(child, dict):
                        if "text" in child:
                            texts.append(child["text"])
                        for sub in child.get("children", []):
                            if isinstance(sub, dict) and "text" in sub:
                                texts.append(sub["text"])
            elif btype == "table":
                for row in blk.get("children", []):
                    if not isinstance(row, dict) or row.get("type") != "table-row":
                        continue
                    for cell in row.get("children", []):
                        if not isinstance(cell, dict) or cell.get("type") != "table-cell":
                            continue
                        for child in cell.get("children", []):
                            if isinstance(child, dict):
                                if "text" in child:
                                    texts.append(child["text"])
                                for sub in child.get("children", []):
                                    if isinstance(sub, dict) and "text" in sub:
                                        texts.append(sub["text"])
            elif btype == "block-code":
                for child in blk.get("children", []):
                    if isinstance(child, dict):
                        for sub in child.get("children", []):
                            if isinstance(sub, dict) and "text" in sub:
                                texts.append(sub["text"])
        return texts

    # ─── Check 2: Text content ───
    if "text_content" in check_types:
        src_texts = _extract_text(source_blocks)
        tgt_texts = _extract_text(target_blocks)
        src_joined = " ".join(t for t in src_texts if t.strip())
        tgt_joined = " ".join(t for t in tgt_texts if t.strip())

        # Check for missing text segments
        missing_texts = []
        for text in src_texts:
            text_stripped = text.strip()
            if text_stripped and len(text_stripped) > 3 and text_stripped not in tgt_joined:
                missing_texts.append(text_stripped[:80])

        check = {
            "type": "text_content",
            "source_text_count": len(src_texts),
            "target_text_count": len(tgt_texts),
            "source_char_count": len(src_joined),
            "target_char_count": len(tgt_joined),
            "missing_segments": len(missing_texts),
        }
        if not missing_texts:
            check["status"] = "pass"
        elif len(missing_texts) <= 2:
            check["status"] = "warn"
            overall_status = "warn" if overall_status == "pass" else overall_status
        else:
            check["status"] = "fail"
            overall_status = "fail"
        checks.append(check)
        if missing_texts:
            losses.append({"type": "missing_text", "segments": missing_texts[:10]})

    # ─── Check 3: Table structure ───
    if "table_structure" in check_types:
        def _count_tables(blocks):
            tables = []
            for blk in blocks:
                if isinstance(blk, dict) and blk.get("type") == "table":
                    rows = [r for r in blk.get("children", []) if isinstance(r, dict) and r.get("type") == "table-row"]
                    col_counts = []
                    for row in rows:
                        cells = [c for c in row.get("children", []) if isinstance(c, dict) and c.get("type") == "table-cell" and not c.get("hidden")]
                        col_counts.append(len(cells))
                    tables.append({"rows": len(rows), "max_cols": max(col_counts) if col_counts else 0})
            return tables

        src_tables = _count_tables(source_blocks)
        tgt_tables = _count_tables(target_blocks)

        table_issues = []
        for i, src_t in enumerate(src_tables):
            if i >= len(tgt_tables):
                table_issues.append(f"表格 {i+1} 丢失")
            else:
                tgt_t = tgt_tables[i]
                if src_t["rows"] != tgt_t["rows"]:
                    table_issues.append(f"表格 {i+1} 行数不匹配：源 {src_t['rows']} 行，目标 {tgt_t['rows']} 行")
                if src_t["max_cols"] != tgt_t["max_cols"]:
                    table_issues.append(f"表格 {i+1} 列数不匹配：源 {src_t['max_cols']} 列，目标 {tgt_t['max_cols']} 列")

        check = {
            "type": "table_structure",
            "source_table_count": len(src_tables),
            "target_table_count": len(tgt_tables),
            "issues": table_issues,
        }
        if not table_issues:
            check["status"] = "pass"
        else:
            check["status"] = "fail" if len(table_issues) > 2 else "warn"
            overall_status = "fail" if len(table_issues) > 2 else ("warn" if overall_status == "pass" else overall_status)
        checks.append(check)
        if table_issues:
            losses.append({"type": "table_structure_mismatch", "issues": table_issues})

    # ─── Check 4: Formatting attributes ───
    if "formatting" in check_types:
        def _count_format_attrs(blocks):
            count = {"bold": 0, "italic": 0, "fontColor": 0, "bgColor": 0, "align": 0}
            def _walk(node):
                if isinstance(node, dict):
                    for attr in count:
                        if node.get(attr):
                            count[attr] += 1
                    for child in node.get("children", []):
                        _walk(child)
            for blk in blocks:
                _walk(blk)
            return count

        src_fmt = _count_format_attrs(source_blocks)
        tgt_fmt = _count_format_attrs(target_blocks)

        format_losses = {}
        for attr in src_fmt:
            if src_fmt[attr] > 0 and tgt_fmt[attr] < src_fmt[attr]:
                format_losses[attr] = {"source": src_fmt[attr], "target": tgt_fmt[attr], "lost": src_fmt[attr] - tgt_fmt[attr]}

        check = {
            "type": "formatting",
            "source_format_counts": src_fmt,
            "target_format_counts": tgt_fmt,
            "format_losses": format_losses,
        }
        if not format_losses:
            check["status"] = "pass"
        else:
            total_lost = sum(v["lost"] for v in format_losses.values())
            check["status"] = "fail" if total_lost > 5 else "warn"
            overall_status = "fail" if total_lost > 5 else ("warn" if overall_status == "pass" else overall_status)
        checks.append(check)
        if format_losses:
            losses.append({"type": "format_loss", "details": format_losses})

    # ─── Check 5: Images ───
    if "images" in check_types:
        def _count_images(blocks):
            urls = set()
            def _walk(node):
                if isinstance(node, dict):
                    if node.get("type") == "img" and node.get("url"):
                        urls.add(node["url"])
                    for child in node.get("children", []):
                        _walk(child)
            for blk in blocks:
                _walk(blk)
            return urls

        src_imgs = _count_images(source_blocks)
        tgt_imgs = _count_images(target_blocks)
        missing_imgs = src_imgs - tgt_imgs

        check = {
            "type": "images",
            "source_image_count": len(src_imgs),
            "target_image_count": len(tgt_imgs),
            "missing_images": len(missing_imgs),
        }
        if not missing_imgs:
            check["status"] = "pass"
        else:
            check["status"] = "fail" if len(missing_imgs) > 2 else "warn"
            overall_status = "fail" if len(missing_imgs) > 2 else ("warn" if overall_status == "pass" else overall_status)
        checks.append(check)
        if missing_imgs:
            losses.append({"type": "missing_images", "urls": list(missing_imgs)[:5]})

    # ─── Auto-fix ───
    fix_applied = None
    if auto_fix and overall_status != "pass" and source_blocks:
        fix_page_id = params.get("fix_page_id", target_page_id)
        import copy
        fix_blocks = copy.deepcopy(source_blocks)
        import uuid as _uuid
        for b in fix_blocks:
            if isinstance(b, dict) and "id" in b:
                b["id"] = _uuid.uuid4().hex[:8]
            for child in b.get("children", []):
                if isinstance(child, dict) and "id" in child:
                    child["id"] = _uuid.uuid4().hex[:8]

        fix_result = create_doc_routing(client, {
            "title": params.get("fix_title", "质检修复版"),
            "content": fix_blocks,
            "team_id": params.get("team_id", "root"),
            "folder_id": params.get("folder_id", "root"),
        })
        fix_applied = {
            "method": "recreate_from_source_blocks",
            "new_page_id": (fix_result.get("data") or {}).get("id"),
            "result_status": fix_result.get("status"),
        }

    result = {
        "status": overall_status,
        "checks": checks,
        "losses": losses,
        "source_block_count": len(source_blocks),
        "target_block_count": len(target_blocks),
    }
    if fix_applied:
        result["fix_applied"] = fix_applied
    if losses:
        result["summary"] = f"检测到 {len(losses)} 类内容损失，总体状态: {overall_status}"
    else:
        result["summary"] = "内容完整性校验通过，无损失"
    return result


def list_doc_by_page(client: JoySpaceClient, params: dict) -> dict:
    query_params = {
        "folderId": params.get("folder_id", "root"),
        "length": str(params.get("length", 20)),
        "start": str(params.get("start", 0)),
        "sort": params.get("sort", "-created_at"),
    }
    if params.get("team_id") and params["team_id"] != "root":
        query_params["teamId"] = params["team_id"]
    return client.joyspace_get("/v1/pages", query_params)


def list_folder_children(client: JoySpaceClient, params: dict) -> dict:
    """枚举文件夹下的子项文档/子文件夹（含page_id、标题、作者、发布时间、是否文件夹）。

    这是 list_doc_by_page 的正确替代：list_doc_by_page 用的 /v1/pages?folderId= 接口
    不按文件夹过滤（返回团队级列表），本函数用的 /v1/spaces/{teamId}/pages?categoryId={folderId}
    是 JoySpace 前端实际使用的接口，能正确返回指定文件夹内的文档列表。

    通过 CDP 抓包（playwright-cli-jd-windows-cdp 打开文件夹页 + Network.enable）发现此接口。
    必填: team_id, folder_id(categoryId)。可选: start(默认0), length(默认40), sort(默认-offset)。
    返回 data.total + data.pages[]，每页含 id(page_id)/title/author/published_at/isParent/is_folder。
    子文件夹的 id 即为下钻用的 folder_id，可递归调用本函数枚举。
    """
    team_id = params.get("team_id")
    folder_id = params.get("folder_id")
    if not team_id or not folder_id:
        return {"status": "failed", "errMsg": "list_folder_children 需要 team_id 和 folder_id(categoryId)"}
    query_params = {
        "categoryId": folder_id,
        "sort": params.get("sort", "-offset"),
        "start": str(params.get("start", 0)),
        "length": str(params.get("length", 40)),
    }
    return client.joyspace_get(f"/v1/spaces/{team_id}/pages", query_params)


def list_folder_subfolders(client: JoySpaceClient, params: dict) -> dict:
    """枚举文件夹下的子文件夹（/v1/folders/{folderId}/children）。
    必填: team_id, folder_id。返回子文件夹列表。"""
    team_id = params.get("team_id")
    folder_id = params.get("folder_id")
    if not team_id or not folder_id:
        return {"status": "failed", "errMsg": "list_folder_subfolders 需要 team_id 和 folder_id"}
    query_params = {"teamId": team_id, "sort": params.get("sort", "-offset")}
    return client.joyspace_get(f"/v1/folders/{folder_id}/children", query_params)


def list_folders(client: JoySpaceClient, params: dict) -> dict:
    query_params = {
        "folderId": params.get("folder_id", "root"),
        "length": "100",
    }
    if params.get("team_id") and params["team_id"] != "root":
        query_params["teamId"] = params["team_id"]
    result = client.joyspace_get("/v1/pages", query_params)
    if isinstance(result, dict) and result.get("status") == "success":
        items = result.get("data", [])
        folders = [i for i in items if i.get("page_type") == 0]
        result["data"] = folders
    return result


def create_folder(client: JoySpaceClient, params: dict) -> dict:
    parent_folder_id = params.get("folder_id", "root")
    payload = {
        "teamId": params["team_id"],
        "parentFolderId": parent_folder_id,
        "name": params["name"],
    }
    result = client.joyspace_post("/v1/folders", payload)
    # API does not return parent in response — inject from request params
    if isinstance(result, dict) and result.get("status") == "success" and result.get("data"):
        result["data"]["parentFolderId"] = parent_folder_id
    return result


def get_folder_info(client: JoySpaceClient, params: dict) -> dict:
    folder_id = params["folder_id"]
    return client.joyspace_get(f"/v2/folders/{folder_id}", {"sendRecent": "0"})


def get_page_basic_info(client: JoySpaceClient, params: dict) -> dict:
    page_id = params["page_id"]
    try:
        return client.joyspace_get(f"/v3/pages/{page_id}/basic", {"sendRecent": "0"})
    except Exception:
        return client.joyspace_get(f"/v2/pages/{page_id}/basic")


def get_normal_json_content(client: JoySpaceClient, params: dict) -> dict:
    payload = {"pageId": params["page_id"]}
    return client.joyspace_post("/v1/pages/content", payload)


def get_normal_markdown_content(client: JoySpaceClient, params: dict) -> dict:
    payload = {"pageId": params["page_id"]}
    result = client.joyspace_post("/v1/pages/markdown-content", payload)
    if isinstance(result, dict) and result.get("status") == "failed":
        raise RuntimeError(f"获取 Markdown 内容失败: {result}")
    return result


def delete_page(client: JoySpaceClient, params: dict) -> dict:
    page_id = params["page_id"]
    return client.joyspace_delete(f"/v1/pages/{page_id}")


def publish_comment(client: JoySpaceClient, params: dict) -> dict:
    """发表评论"""
    page_id = params["page_id"]
    content = params["content"]
    comment_ops = json.dumps([{"insert": f"{content}\n"}])
    request_data = {
        "content": comment_ops,
        "comment_visible": 1,
        "content_type": 2,
        "reply_id": -1,
        "reply_user_id": "",
        "selected_id": "",
        "mentionUsers": [],
        "notifyAllCoops": False,
    }
    return client.joyspace_post(f"/v1/pages/{page_id}/page_comments", request_data)


def _resolve_user_id(client: JoySpaceClient, identifier: str) -> str:
    """将用户标识解析为 JoySpace 内部用户 ID。
    如果 identifier 看起来像 JoySpace ID (含下划线/连字符的短ID)，直接返回。
    否则当作 erp 用户名，调用 /v1/users/search 查询。
    """
    if not identifier:
        return identifier
    # JoySpace internal IDs are short alphanumeric with _ or -, e.g. "i_i7EMT-nEYfMlBPFkEA"
    if re.match(r'^[a-zA-Z0-9_-]{10,}$', identifier) and not re.match(r'^[a-zA-Z]+\d+$', identifier):
        return identifier
    # Treat as erp username, search for internal ID
    try:
        result = client.joyspace_get("/v1/users/search", {"search": identifier})
        users = result.get("data", []) if isinstance(result, dict) else []
        for u in users:
            if u.get("username") == identifier:
                return u["id"]
        # Fallback: return first match if any
        if users:
            return users[0]["id"]
    except Exception:
        pass
    return identifier


def share_to_contact(client: JoySpaceClient, params: dict) -> dict:
    """分享文档给联系人"""
    page_id = params["page_id"]
    user_id = _resolve_user_id(client, params.get("employee_id", params.get("user_id", "")))
    request_data = {
        "page_id": page_id,
        "to_groups": [],
        "to_mail_groups": [],
        "to_orgs": [],
        "to_users": [
            {
                "id": user_id,
                "permission_type": params.get("permission_type", 2),
            }
        ],
        "content": params.get("content", ""),
        "sendToChat": params.get("send_to_chat", True),
        "watchComment": params.get("watch_comment", 0),
        "scene": params.get("scene", "SharebyButtontoChat"),
    }
    return client.joyspace_post("/v1/shares", request_data)


def update_page(client: JoySpaceClient, params: dict) -> dict:
    """更新文档元数据（标题、字数等）。注意：文档正文内容通过协作编辑WebSocket更新，不走此API。"""
    page_id = params["page_id"]
    data = {}
    if "title" in params:
        data["title"] = params["title"]
    if "word_num" in params:
        data["word_num"] = params["word_num"]
    if "preview_text" in params:
        data["preview_text"] = params["preview_text"]
    return client.joyspace_post(f"/v2/pages/{page_id}/update", data)


def get_page_location(client: JoySpaceClient, params: dict) -> dict:
    """获取文档所在的位置路径（团队 → 文件夹层级）"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v2/pages/{page_id}/location")


def list_comments(client: JoySpaceClient, params: dict) -> dict:
    """列出文档的评论"""
    page_id = params["page_id"]
    query_params = {}
    if "start" in params:
        query_params["start"] = str(params["start"])
    if "length" in params:
        query_params["length"] = str(params["length"])
    return client.joyspace_get(f"/v1/pages/{page_id}/page_comments", query_params or None)


def reply_comment(client: JoySpaceClient, params: dict) -> dict:
    """回复评论（使用同一端点，设reply_id为父评论ID）"""
    page_id = params["page_id"]
    comment_id = params["comment_id"]
    content = params["content"]
    reply_user_id = params.get("reply_user_id", "")
    comment_ops = json.dumps([{"insert": f"{content}\n"}])
    request_data = {
        "content": comment_ops,
        "comment_visible": 1,
        "content_type": 2,
        "reply_id": comment_id,
        "reply_user_id": reply_user_id,
        "selected_id": "",
        "mentionUsers": [],
        "notifyAllCoops": False,
    }
    return client.joyspace_post(f"/v1/pages/{page_id}/page_comments", request_data)


def delete_comment(client: JoySpaceClient, params: dict) -> dict:
    """删除评论"""
    page_id = params["page_id"]
    comment_id = params["comment_id"]
    return client.joyspace_delete(f"/v1/pages/{page_id}/page_comments/{comment_id}")


def update_share_permission(client: JoySpaceClient, params: dict) -> dict:
    """更新用户权限（通过重新分享修改permission_type）"""
    page_id = params["page_id"]
    user_id = _resolve_user_id(client, params.get("user_id", params.get("employee_id", "")))
    permission_type = params.get("permission_type", 2)
    request_data = {
        "page_id": page_id,
        "to_groups": [],
        "to_mail_groups": [],
        "to_orgs": [],
        "to_users": [{"id": user_id, "permission_type": permission_type}],
        "content": params.get("content", ""),
        "sendToChat": params.get("send_to_chat", False),
        "watchComment": params.get("watch_comment", 0),
        "scene": params.get("scene", "SharebyButtontoChat"),
    }
    return client.joyspace_post("/v1/shares", request_data)


def update_page_settings(client: JoySpaceClient, params: dict) -> dict:
    """更新文档设置。

    核心参数：
    - adaptiveLayout: "0"=标宽页面, "1"=超宽页面（必须为字符串，不能传布尔值）
    """
    page_id = params["page_id"]
    settings = {k: v for k, v in params.items() if k not in ("page_id",)}
    # Fix: adaptiveLayout must be string "0" or "1", not boolean
    if "adaptiveLayout" in settings:
        val = settings["adaptiveLayout"]
        if isinstance(val, bool):
            settings["adaptiveLayout"] = "1" if val else "0"
        elif isinstance(val, (int, float)):
            settings["adaptiveLayout"] = str(int(val))
    return client.joyspace_post(f"/v1/pages/{page_id}/settings", settings)


def get_share_members(client: JoySpaceClient, params: dict) -> dict:
    """获取文档的分享成员列表及权限"""
    request_data = {
        "page_id": params["page_id"],
        "start": params.get("start", 0),
        "length": params.get("length", 50),
    }
    return client.joyspace_post("/v1/shares/members", request_data)


def move_page(client: JoySpaceClient, params: dict) -> dict:
    """移动文档到指定文件夹/团队

    NOTE: /v2/pages/{id}/move REST端点目前返回"未知错误"，这是后端限制。
    作为替代，可通过 copy_page + delete_page 实现等效移动。
    """
    page_id = params["page_id"]
    folder_id = params.get("folder_id", "")
    team_id = params.get("team_id", "")

    # 先尝试 REST API
    data = {}
    if folder_id:
        data["folderId"] = folder_id
    if team_id:
        data["teamId"] = team_id
    result = client.joyspace_post(f"/v2/pages/{page_id}/move", data)
    if result.get("status") == "failed":
        # REST API 失败，尝试 copy+delete 替代方案
        copy_result = copy_page(client, {"page_id": page_id, "folder_id": folder_id, "team_id": team_id})
        if copy_result.get("status") == "success":
            delete_page(client, {"page_id": page_id})
            copy_result["_moved_via_copy_delete"] = True
            return copy_result
    return result


def copy_page(client: JoySpaceClient, params: dict) -> dict:
    """复制文档到指定文件夹/团队"""
    page_id = params["page_id"]
    # Get source page info for pageType
    source_info = get_page_basic_info(client, {"page_id": page_id})
    page_type = 13
    if isinstance(source_info, dict):
        page_data = source_info.get("data", source_info)
        page_type = page_data.get("page_type", page_data.get("pageType", 13))
    data = {
        "copyFrom": page_id,
        "pageType": page_type,
        "teamId": params.get("team_id", "root"),
        "folderId": params.get("folder_id", "root"),
    }
    if "title" in params:
        data["title"] = params["title"]
    else:
        data["title"] = ""
    return client.joyspace_post("/v2/pages", data)


def get_page_history(client: JoySpaceClient, params: dict) -> dict:
    """获取文档的编辑历史"""
    page_id = params["page_id"]
    query_params = {}
    if "start" in params:
        query_params["start"] = str(params["start"])
    if "length" in params:
        query_params["length"] = str(params["length"])
    return client.joyspace_get(f"/v1/pages/{page_id}/history", query_params or None)


def export_page(client: JoySpaceClient, params: dict) -> dict:
    """导出文档（支持 pdf/markdown 等格式）"""
    page_id = params["page_id"]
    data = {
        "pageId": page_id,
        "format": params.get("format", "pdf"),
    }
    return client.joyspace_post(f"/v1/pages/{page_id}/export", data)


def get_page_snapshot(client: JoySpaceClient, params: dict) -> dict:
    """获取文档快照（仅部分类型支持，如PPT）"""
    page_id = params["page_id"]
    query_params = {"page_id": page_id}
    return client.joyspace_get(f"/v1/pages/{page_id}/snapshot", query_params)


def get_page_basic_info_v1(client: JoySpaceClient, params: dict) -> dict:
    """获取文档v1基础信息（含pageType/valid/name等，比v3更简洁）"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v1/pages/{page_id}/getBasicInfo")


def get_origin_id(client: JoySpaceClient, params: dict) -> dict:
    """获取文档原始ID（用于blog/旧表格等多版本页面）"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v1/pages/{page_id}/getOriginId")


def get_page_likes(client: JoySpaceClient, params: dict) -> dict:
    """获取文档点赞列表"""
    page_id = params["page_id"]
    query_params = {"start": str(params.get("start", 0)), "length": str(params.get("length", 9))}
    return client.joyspace_get(f"/v1/pages/{page_id}/like/page", query_params)


def get_referenced_list(client: JoySpaceClient, params: dict) -> dict:
    """获取引用此文档的页面列表"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v1/pages/{page_id}/referencedList")


def get_sensitive_list(client: JoySpaceClient, params: dict) -> dict:
    """获取文档的敏感数据标记列表"""
    page_id = params["page_id"]
    biz_type = params.get("biz_type", 1)
    return client.joyspace_get(f"/v1/sensitive/list", {"bizId": page_id, "bizType": str(biz_type)})


def get_watch_list(client: JoySpaceClient, params: dict) -> dict:
    """获取文档的关注/订阅状态"""
    page_id = params["page_id"]
    biz_type = params.get("biz_type", 1)
    return client.joyspace_get(f"/v1/watch/list", {"bizId": page_id, "bizType": str(biz_type)})


def get_tags(client: JoySpaceClient, params: dict) -> dict:
    """获取文档的标签"""
    page_id = params["page_id"]
    biz_type = params.get("biz_type", 1)
    category_id = params.get("category_id", 3)
    return client.joyspace_get(f"/v1/tags/biz-tag-ref", {"bizType": str(biz_type), "bizId": page_id, "categoryId": str(category_id)})


def get_task_num(client: JoySpaceClient, params: dict) -> dict:
    """获取文档关联的任务数"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v3/pages/{page_id}/task-num")


def get_read_state(client: JoySpaceClient, params: dict) -> dict:
    """获取文档的已读/未读状态"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v2/share-record/getReadState", {"pageId": page_id})


def get_shimo_auth(client: JoySpaceClient, params: dict) -> dict:
    """获取石墨（ShiMo）编辑器认证信息（用于blog/旧表格/多维表的协作编辑）"""
    page_id = params["page_id"]
    return client.joyspace_post(f"/v1/sm/getShiMoAuthorityInfo", {"pageId": page_id})


def get_wiki_files(client: JoySpaceClient, params: dict) -> dict:
    """获取知识库(Wiki)类型的文件信息"""
    page_id = params["page_id"]
    return client.joyspace_get(f"/v1/web-files/{page_id}")
