"""Table styling, layout optimization, and content verification for JoySpace documents."""

import copy
import json
import time
import uuid

from .gateway import JoySpaceClient
from .doc_create import create_doc_routing
from .doc_read import get_normal_json_content
from .doc_markdown import (
    STANDARD_PAGE_CONTENT_WIDTH,
    ULTRAWIDE_TABLE_AVAILABLE_WIDTH,
    _detect_width_from_blocks,
)


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。
        col_styles (dict): 指定列的样式，key为列索引，value为样式dict。
        cell_styles (list): 指定单元格的样式列表
        global_bold (bool): 全局加粗所有文字
        global_font_color (str): 全局字体颜色
    """
    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} 内容为空"}
        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 参数"}

    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")

    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):
        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):
        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)

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

        if global_bold or global_font_color:
            btype = block.get("type", "")
            if btype in ("p", "list", "block-quote", "foldable-block", "encrypted-block", "highlight-block"):
                _apply_text_style(
                    block.get("children", []),
                    bold=global_bold,
                    font_color=global_font_color,
                )

        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

                    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)

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

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

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

                    cell_key = (row_idx, col_idx)
                    if cell_key in cell_style_map:
                        _apply_cell_style(cell_node, cell_style_map[cell_key])

    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:
    """批量优化文档中所有表格的宽度和对齐。"""
    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,
    )

    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} 内容为空"}
        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)

    page_width_mode = None
    if auto_page_width:
        page_width_mode = _detect_width_from_blocks(blocks)

    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

        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

        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
                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())

        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)

        min_col_w = 56
        current_total = sum(col_widths)

        if current_total > page_w:
            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
        elif fill_page_width and current_total > page_w * 0.6:
            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

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

        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)

        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

                cell_node["verticalAlign"] = body_valign

                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

    title = params.get("title", "排版优化版")
    create_params = {
        "title": title,
        "content": blocks,
        "team_id": params.get("team_id", "root"),
        "folder_id": params.get("folder_id", "root"),
    }
    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
    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"
    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":
                for sub in child.get("children", []):
                    if isinstance(sub, dict) and sub.get("type") == "p":
                        sub["align"] = align
            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:
    """质检动作：对比源内容与实际内容，检测损失。"""
    target_page_id = params.get("target_page_id")
    if not target_page_id:
        return {"status": "error", "error": "必须提供 target_page_id 参数"}

    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 参数"}

    time.sleep(2)
    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"

    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)})

    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"])
            elif btype in ("foldable-block", "encrypted-block"):
                texts.extend(_extract_text(blk.get("children", [])))
        return texts

    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())

        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]})

    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})

    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})

    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]})

    fix_applied = None
    if auto_fix and overall_status != "pass" and source_blocks:
        fix_page_id = params.get("fix_page_id", target_page_id)
        fix_blocks = copy.deepcopy(source_blocks)
        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
