# generators/generate_md_tag_table.py
# -*- coding: utf-8 -*-


def generate_tag_table_markdown(data):
    """Genera contenido Markdown para una tabla de tags."""
    md_lines = []
    table_name = data.get("block_name", "UnknownTagTable")
    tags = data.get("tags", [])
    block_number = data.get("block_number")
    block_type = data.get("block_type", "TagTable")

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

    md_lines.append(f"# Tag Table: {table_name}")
    md_lines.append("")

    if tags:
        md_lines.append("| Name | Datatype | Address | Comment |")
        md_lines.append("|---|---|---|---|")
        for tag in tags:
            name = tag.get("name", "N/A")
            datatype = tag.get("datatype", "N/A")
            address = tag.get("address", "N/A") or " "
            comment_raw = tag.get("comment")
            comment = (
                comment_raw.replace("|", "\|").replace("\n", " ") if comment_raw else ""
            )
            md_lines.append(f"| `{name}` | `{datatype}` | `{address}` | {comment} |")
        md_lines.append("")
    else:
        md_lines.append("No tags found in this table.")
        md_lines.append("")

    return md_lines
