"""Markdown-to-Slate conversion and page width detection for JoySpace documents."""

import json
import random
import re
import uuid


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


_BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"


def _gen_encrypt_id():
    """Generate a 20-char base62 ID for encrypted-block encryptId field."""
    return "".join(random.choices(_BASE62, k=20))


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

        # Encrypted block: <details data-encrypted [data-encrypt-id="xxx"]><summary>...</summary>
        m = re.match(r'^<details\s+data-encrypted\b', line, re.IGNORECASE)
        if m:
            encrypt_id = ""
            # Extract data-encrypt-id from the opening tag
            eid_m = re.search(r'data-encrypt-id\s*=\s*"([^"]*)"', line, re.IGNORECASE)
            if eid_m:
                encrypt_id = eid_m.group(1)
            if not encrypt_id:
                encrypt_id = _gen_encrypt_id()
            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="")
            enc = {'type': 'encrypted-block', 'id': _gen_id(), 'encryptId': encrypt_id, 'children': inner_blocks}
            blocks.append(enc)
            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('```'):
            raw_lang = line.strip()[3:].strip()
            lang = raw_lang
            is_fold = False
            is_wrap = False
            # Parse fold:lang or fold:lang:wrap syntax
            if raw_lang.lower().startswith('fold:'):
                is_fold = True
                rest = raw_lang[5:]
                parts = rest.split(':')
                lang = parts[0] if parts else ""
                is_wrap = 'wrap' in parts[1:] if len(parts) > 1 else False
            code_lines = []
            i += 1
            while i < len(lines) and not lines[i].strip().startswith('```'):
                code_lines.append(lines[i])
                i += 1
            i += 1
            block = {
                'type': 'block-code', 'id': _gen_id(), 'lang': lang,
                'children': [{'type': 'block-code-line', 'id': _gen_id(), 'children': [{'text': cl}]} for cl in code_lines]
            }
            if is_fold:
                block['fold'] = True
                block['codeName'] = '代码块'
            if is_wrap:
                block['wrap'] = True
            blocks.append(block)
            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"
