# -*- coding: utf-8 -*-
"""
import_helpers.py - Rhino 导入脚本公共逻辑

提供 build_elements_by_category / delete_old_layer 等函数，
供 SpanCoreLink 插件的 ImportByGroup/ImportBySection/ImportByMaterial 使用。
"""
import rhinoscriptsyntax as rs
from PySap2000.visualization.rhino.rhino_builder import RhinoBuilder
from PySap2000.geometry.element_geometry import FrameElement3D, CableElement3D


def build_elements_by_category(
    category_elements: dict,
    category_colors: dict,
    root_layer: str,
    create_solid: bool,
) -> tuple:
    """
    按分类生成 Rhino 几何体

    Args:
        category_elements: {分类名: [元素列表]}
        category_colors: {分类名: (r, g, b)}
        root_layer: 根图层名称
        create_solid: 是否创建实体

    Returns:
        (创建的对象 GUID 列表, stats 字典)
    """
    builder = RhinoBuilder()
    total_elements = sum(len(elems) for elems in category_elements.values())

    print("=" * 60)
    print(f"Categories: {len(category_elements)}")
    print(f"Total elements: {total_elements}")
    print(f"Mode: {'Solid' if create_solid else 'Wireframe'}")
    print("=" * 60)

    rs.EnableRedraw(False)

    if not rs.IsLayer(root_layer):
        rs.AddLayer(root_layer)

    all_guids = []
    stats = {"total": 0, "success": 0, "failed": 0}
    processed = 0
    last_progress = -1

    for category, elements in category_elements.items():
        sub_layer = f"{root_layer}::{category}"
        color = category_colors.get(category, (128, 128, 128))

        if not rs.IsLayer(sub_layer):
            rs.AddLayer(sub_layer, color)
        rs.LayerColor(sub_layer, color)

        for elem in elements:
            processed += 1
            current_progress = (processed * 10) // total_elements if total_elements > 0 else 0
            if current_progress > last_progress or processed == total_elements:
                _print_progress(processed, total_elements)
                last_progress = current_progress

            try:
                rs.CurrentLayer(sub_layer)

                if isinstance(elem, FrameElement3D):
                    if create_solid:
                        guid = builder._build_frame_solid(elem, num_segments=8)
                    else:
                        guid = builder._build_frame_line(elem)
                elif isinstance(elem, CableElement3D):
                    if create_solid:
                        guid = builder._build_cable_solid(elem, num_segments=8)
                    else:
                        guid = builder._build_cable_line(elem)
                else:
                    guid = builder._build_line(elem)

                if guid:
                    all_guids.append(guid)
                    rs.ObjectName(guid, elem.name)
                    rs.ObjectColor(guid, color)
                    stats["success"] += 1
                else:
                    stats["failed"] += 1

                stats["total"] += 1

            except Exception:
                stats["failed"] += 1
                stats["total"] += 1
                continue

    rs.EnableRedraw(True)
    rs.ZoomExtents()

    return all_guids, stats


def delete_old_layer(layer_name: str):
    """删除旧图层及其所有对象"""
    if rs.IsLayer(layer_name):
        print(f"Deleting old layer: {layer_name}")
        old_objects = rs.ObjectsByLayer(layer_name, select=False)
        if old_objects:
            rs.DeleteObjects(old_objects)
        rs.DeleteLayer(layer_name)


def _print_progress(current: int, total: int):
    """打印对齐的进度条"""
    if total == 0:
        return
    progress = current / total
    bar_width = 30
    filled = int(bar_width * progress)
    bar = "█" * filled + "░" * (bar_width - filled)
    percent = int(progress * 100)
    total_width = len(str(total))
    print(f"Progress: [{bar}] {percent:3d}% ({current:>{total_width}}/{total})")
