"""Slate-to-Markdown renderer for JoySpace document block trees.

Reusable rendering engine extracted from joyspace-page-to-markdown.
Converts JoySpace's Slate-like JSON block tree into clean Markdown text.

Usage:
    from utils.slate_renderer import render_blocks, page_to_markdown

Block schema:
    type=p              -> paragraph; fontSize-based heading detection
    type=list           -> list item (bullet/numbered, with indent)
    type=table          -> Markdown table (colSpan expansion, hidden cell skip)
    type=foldable-block -> <details>/<summary> collapsible section
    type=encrypted-block -> <details data-encrypted>/<summary> encrypted section
    type=highlight-block -> blockquote with emoji prefix
    type=img            -> ![](url)
    type=block-code     -> fenced code block (fold=true wraps in <details>)
    type=docfile        -> inline JoySpace doc reference link
    type=mention        -> inline @user reference
    type=link           -> inline external link
"""
from __future__ import annotations

import re
from typing import Any


# Heading thresholds (fontSize -> markdown heading level).
HEADING_FONTSIZE_LEVEL: list[tuple[int, int]] = [
    (32, 1),
    (26, 2),
    (22, 3),
    (18, 4),
    (16, 5),
]


def render_text_span(span: dict[str, Any]) -> str:
    txt = span.get("text", "")
    if not txt:
        return ""
    if span.get("code"):
        return f"`{txt}`"
    # Layer formatting: italic innermost, then bold, then strikethrough outermost
    if span.get("italic"):
        txt = f"*{txt}*"
    if span.get("bold"):
        txt = f"**{txt}**"
    if span.get("strikethrough"):
        txt = f"~~{txt}~~"
    return txt


def _docfile_link(blk: dict[str, Any]) -> str:
    val = blk.get("value") or {}
    title = val.get("title") or val.get("name") or "[文档]"
    page_id = val.get("id")
    if page_id:
        return f"[{title}](https://joyspace.jd.com/pages/{page_id})"
    return title


def _mention_text(blk: dict[str, Any]) -> str:
    val = blk.get("value") or {}
    name = val.get("name") or val.get("title") or val.get("username") or ""
    return f"@{name}" if name else "@"


def render_inline(children: list[Any]) -> str:
    out: list[str] = []
    for c in children:
        if not isinstance(c, dict):
            continue
        t = c.get("type")
        if t is None:
            out.append(render_text_span(c))
        elif t == "link":
            url = c.get("url", "")
            inner = render_inline(c.get("children", []))
            out.append(f"[{inner or url}]({url})")
        elif t == "mention":
            out.append(_mention_text(c))
        elif t == "docfile":
            out.append(_docfile_link(c))
        else:
            inner = render_inline(c.get("children", []))
            out.append(inner)
    return "".join(out)


def heading_level_for_p(blk: dict[str, Any]) -> int | None:
    # Priority 1: explicit `header` field on the block
    header_val = blk.get("header")
    if header_val and isinstance(header_val, int) and 1 <= header_val <= 6:
        return header_val
    # Priority 2: fontSize-based detection (legacy)
    children = blk.get("children", [])
    sizes = [c.get("fontSize") for c in children if isinstance(c, dict) and c.get("fontSize")]
    if not sizes:
        return None
    biggest = max(sizes)
    for threshold, level in HEADING_FONTSIZE_LEVEL:
        if biggest >= threshold:
            return level
    return None


def _is_symbolic_only(text: str) -> bool:
    stripped = text.strip()
    if not stripped:
        return True
    if len(stripped) > 2:
        return False
    return not any(ch.isalnum() for ch in stripped)


def render_paragraph(blk: dict[str, Any], *, force_no_heading: bool = False) -> str:
    text = render_inline(blk.get("children", [])).rstrip()
    if not text:
        return ""
    if not force_no_heading:
        level = heading_level_for_p(blk)
        if level is not None:
            stripped = text.strip()
            if stripped.startswith("**") and stripped.endswith("**") and stripped.count("**") == 2:
                stripped = stripped[2:-2]
            if _is_symbolic_only(stripped):
                return text
            return f"{'#' * level} {stripped}"
    return text


def render_list_item(blk: dict[str, Any]) -> str | None:
    indent = int(blk.get("indent", 0) or 0)
    value = blk.get("value", "bullet")
    marker = "1." if value == "numbered" else "-"
    prefix = "  " * indent + f"{marker} "
    children = blk.get("children", [])
    text_parts: list[str] = []
    extra_lines: list[str] = []
    for c in children:
        if not isinstance(c, dict):
            continue
        t = c.get("type")
        if t == "img":
            url = c.get("url", "")
            if url:
                extra_lines.append(f"![]({url})")
        elif t == "p":
            txt = render_inline(c.get("children", [])).strip()
            if txt:
                text_parts.append(txt)
        elif t is None:
            txt = render_text_span(c).strip()
            if txt:
                text_parts.append(txt)
        else:
            txt = render_inline(c.get("children", [])).strip()
            if txt:
                text_parts.append(txt)
    text = " ".join(text_parts)
    if not text and not extra_lines:
        return None
    indent_prefix = "  " * indent
    result = prefix + text if text else ""
    for line in extra_lines:
        result += f"\n{indent_prefix}  {line}"
    return result


def render_table(blk: dict[str, Any]) -> str:
    rows = blk.get("children", [])
    if not rows:
        return ""
    matrix: list[list[str]] = []
    for row in rows:
        if not isinstance(row, dict) or row.get("type") != "table-row":
            continue
        line: list[str] = []
        for cell in row.get("children", []):
            if not isinstance(cell, dict) or cell.get("type") != "table-cell":
                continue
            if cell.get("hidden"):
                continue
            cell_text_lines: list[str] = []
            for child in cell.get("children", []):
                if not isinstance(child, dict):
                    continue
                if child.get("type") == "p":
                    txt = render_inline(child.get("children", [])).strip()
                    if txt:
                        cell_text_lines.append(txt)
                elif child.get("type") == "list":
                    li = render_list_item(child)
                    if li is not None:
                        cell_text_lines.append(li.strip())
                elif child.get("type") == "block-code":
                    lang = child.get("lang", "")
                    code_lines: list[str] = []
                    for code_child in child.get("children", []):
                        if isinstance(code_child, dict) and code_child.get("type") == "block-code-line":
                            code_lines.append(render_inline(code_child.get("children", [])))
                    if code_lines:
                        cell_text_lines.append(f"```{lang}\n" + "\n".join(code_lines) + "\n```")
                elif "text" in child and not child.get("type"):
                    txt = render_text_span(child).strip()
                    if txt:
                        cell_text_lines.append(txt)
                elif child.get("type") == "link":
                    url = child.get("url", "")
                    inner = render_inline(child.get("children", []))
                    cell_text_lines.append(f"[{inner or url}]({url})")
                elif child.get("type") == "img":
                    url = child.get("url", "")
                    if url:
                        cell_text_lines.append(f"![]({url})")
                else:
                    txt = render_inline(child.get("children", [])).strip()
                    if txt:
                        cell_text_lines.append(txt)
            cell_text = "<br>".join(cell_text_lines).replace("|", "\\|")
            colspan = int(cell.get("colSpan", 1) or 1)
            line.append(cell_text)
            for _ in range(colspan - 1):
                line.append("")
        if line:
            matrix.append(line)
    if not matrix:
        return ""
    width = max(len(r) for r in matrix)
    for r in matrix:
        while len(r) < width:
            r.append("")
    header = matrix[0]
    body = matrix[1:]
    sep = ["---"] * width
    md_lines = ["| " + " | ".join(header) + " |", "| " + " | ".join(sep) + " |"]
    for r in body:
        md_lines.append("| " + " | ".join(r) + " |")
    return "\n".join(md_lines)


def render_blocks(blocks: list[dict[str, Any]]) -> str:
    lines: list[str] = []
    for blk in blocks:
        if not isinstance(blk, dict):
            continue
        t = blk.get("type")
        if t == "p":
            md = render_paragraph(blk)
            lines.append(md)
        elif t == "list":
            li = render_list_item(blk)
            if li is not None:
                lines.append(li)
        elif t == "table":
            lines.append(render_table(blk))
        elif t == "img":
            url = blk.get("url", "")
            alt = blk.get("alt", "")
            if url:
                lines.append(f"![{alt}]({url})" if alt else f"![]({url})")
        elif t == "foldable-block":
            name = blk.get("name", "").strip()
            inner = render_blocks(blk.get("children", []))
            if name:
                lines.append(f"<details>\n<summary>{name}</summary>\n\n{inner}\n\n</details>")
            else:
                lines.append(inner)
        elif t == "encrypted-block":
            encrypt_id = blk.get("encryptId", "")
            inner = render_blocks(blk.get("children", []))
            attr = ' data-encrypted'
            if encrypt_id:
                attr += f' data-encrypt-id="{encrypt_id}"'
            lines.append(f"<details{attr}>\n<summary>🔒 加密内容</summary>\n\n{inner}\n\n</details>")
        elif t == "highlight-block":
            emoji = blk.get("emoji", "")
            inner = render_blocks(blk.get("children", []))
            inner_quoted = "\n".join("> " + ln if ln else ">" for ln in inner.splitlines())
            header = f"> {emoji}".rstrip()
            if inner_quoted:
                lines.append(f"{header}\n{inner_quoted}")
            else:
                lines.append(header)
        elif t == "docfile":
            lines.append(_docfile_link(blk))
        elif t == "block-code":
            lang = blk.get("lang", "")
            is_fold = blk.get("fold", False)
            code_lines: list[str] = []
            for code_child in blk.get("children", []):
                if not isinstance(code_child, dict):
                    continue
                if code_child.get("type") == "block-code-line":
                    line_text = render_inline(code_child.get("children", []))
                    code_lines.append(line_text)
                else:
                    line_text = render_inline(code_child.get("children", []))
                    if line_text:
                        code_lines.append(line_text)
            code_body = "\n".join(code_lines)
            code_md = f"```{lang}\n{code_body}\n```"
            if is_fold:
                summary = f"代码: {lang}" if lang else "代码"
                lines.append(f"<details>\n<summary>{summary}</summary>\n\n{code_md}\n\n</details>")
            else:
                lines.append(code_md)
        elif t == "divider":
            lines.append("---")
        elif t == "block-quote":
            inner = render_inline(blk.get("children", []))
            if inner:
                lines.append(f"> {inner}")
        else:
            inner = render_blocks(blk.get("children", []))
            if inner:
                lines.append(inner)
    # Join with blank lines, but list items should stay close together.
    out: list[str] = []
    prev_was_list = False
    for ln in lines:
        if not ln:
            continue
        is_list = ln.lstrip().startswith(("- ", "1. ")) or re.match(r"^\s*1\. ", ln)
        if out and not (prev_was_list and is_list):
            out.append("")
        out.append(ln)
        prev_was_list = bool(is_list)
    return "\n".join(out)


def page_to_markdown(info: dict[str, Any], content_blocks: list[dict[str, Any]]) -> tuple[str, str]:
    """Convert page info + content blocks to (title, body_markdown).

    Handles title extraction from first paragraph if not present in info.
    """
    title = info.get("name") or info.get("title") or ""

    blocks = list(content_blocks)
    if blocks:
        first = blocks[0]
        if isinstance(first, dict) and first.get("type") == "p":
            level = heading_level_for_p(first)
            first_text = render_inline(first.get("children", [])).strip()
            if first_text.startswith("**") and first_text.endswith("**") and first_text.count("**") == 2:
                first_text_plain = first_text[2:-2]
            else:
                first_text_plain = first_text
            if level is None and first_text_plain:
                if not title:
                    title = first_text_plain
                if first_text_plain == title:
                    blocks = blocks[1:]

    if not title:
        title = "JoySpace Page"

    body = render_blocks(blocks)
    return title, body
