# generators/generate_md_udt.py
# -*- coding: utf-8 -*-
import re
from .generator_utils import format_scl_start_value  # Importar utilidad necesaria


def generate_markdown_member_rows(members, level=0):
    """Genera filas Markdown para miembros de UDT (recursivo)."""
    md_rows = []
    prefix = "&nbsp;&nbsp;&nbsp;&nbsp;" * level
    for member in members:
        name = member.get("name", "N/A")
        datatype = member.get("datatype", "N/A")
        start_value_raw = member.get("start_value")
        start_value_fmt = (
            format_scl_start_value(start_value_raw, datatype)
            if start_value_raw is not None
            else ""
        )
        comment_raw = member.get("comment")
        comment = (
            comment_raw.replace("|", "\|").replace("\n", " ") if comment_raw else ""
        )
        md_rows.append(
            f"| {prefix}`{name}` | `{datatype}` | `{start_value_fmt}` | {comment} |"
        )
        children = member.get("children")
        if children:
            md_rows.extend(generate_markdown_member_rows(children, level + 1))
        array_elements = member.get("array_elements")
        if array_elements:
            base_type_for_init = datatype
            if isinstance(datatype, str) and datatype.lower().startswith("array["):
                match = re.match(r"(Array\[.*\]\s+of\s+)(.*)", datatype, re.IGNORECASE)
                if match:
                    base_type_for_init = match.group(2).strip()
            md_rows.append(f"| {prefix}&nbsp;&nbsp;*(Initial Values)* |  |  |  |")
            try:
                indices_numeric = {int(k): v for k, v in array_elements.items()}
                sorted_indices_str = [str(k) for k in sorted(indices_numeric.keys())]
            except ValueError:
                sorted_indices_str = sorted(array_elements.keys())
            for idx_str in sorted_indices_str:
                val_raw = array_elements[idx_str]
                val_fmt = (
                    format_scl_start_value(val_raw, base_type_for_init)
                    if val_raw is not None
                    else ""
                )
                md_rows.append(
                    f"| {prefix}&nbsp;&nbsp;`[{idx_str}]` | | `{val_fmt}` | |"
                )
    return md_rows


def generate_udt_markdown(data):
    """Genera contenido Markdown para un UDT."""
    md_lines = []
    udt_name = data.get("block_name", "UnknownUDT")
    udt_comment = data.get("block_comment", "")
    block_number = data.get("block_number")
    block_type = data.get("block_type", "UDT")

    # Agregar línea de identificación del bloque al inicio
    if block_number and block_type:
        if block_type == "PlcUDT" or block_type == "UDT":
            md_lines.append(f"<!-- UDT{block_number} -->")
        else:
            md_lines.append(f"<!-- {block_type}{block_number} -->")
    elif block_type:
        md_lines.append(f"<!-- {block_type} -->")

    md_lines.append(f"# UDT: {udt_name}")
    md_lines.append("")
    if udt_comment:
        md_lines.append(f"**Comment:**")
        [md_lines.append(f"> {line}") for line in udt_comment.splitlines()]
        md_lines.append("")
    members = data.get("interface", {}).get("None", [])
    if members:
        md_lines.append("## Members")
        md_lines.append("")
        md_lines.append("| Name | Datatype | Start Value | Comment |")
        md_lines.append("|---|---|---|---|")
        md_lines.extend(generate_markdown_member_rows(members))
        md_lines.append("")
    else:
        md_lines.append("No members found in the UDT interface.")
        md_lines.append("")
    return md_lines
