# ToUpload/generators/generate_scl_db.py
# -*- coding: utf-8 -*-
# No necesita importar json/os aquí, lo hará generate_scl_declarations
from .generator_utils import format_variable_name, generate_scl_declarations


# Modificar _generate_scl_header si es necesario, pero parece ok
def _generate_scl_header(data, scl_block_name):
    # ... (código sin cambios) ...
    scl_output = []
    block_type = data.get("block_type", "Unknown")
    block_name = data.get("block_name", "UnknownBlock")
    block_number = data.get("block_number")
    block_comment = data.get("block_comment", "")

    # Agregar línea de identificación del bloque al inicio
    if block_number and block_type:
        if block_type == "GlobalDB":
            scl_output.append(f"// DB{block_number}")
        elif block_type == "InstanceDB":
            scl_output.append(f"// DB{block_number}")
        else:
            # Para otros tipos de DB
            scl_output.append(f"// DB{block_number}")
    elif block_type:
        scl_output.append(f"// {block_type}")

    scl_output.append(f"// Block Type: {block_type}")
    if block_name != scl_block_name:
        scl_output.append(f"// Block Name (Original): {block_name}")
    if block_number:
        scl_output.append(f"// Block Number: {block_number}")
    if block_comment:
        scl_output.append(f"// Block Comment:")
        [scl_output.append(f"//   {line}") for line in block_comment.splitlines()]
    scl_output.append("")
    scl_output.append(f'DATA_BLOCK "{scl_block_name}"')
    scl_output.append("{ S7_Optimized_Access := 'TRUE' }")
    scl_output.append("VERSION : 0.1")
    scl_output.append("")
    return scl_output


# Modificar _generate_scl_interface para pasar project_root_dir
def _generate_scl_interface(interface_data, project_root_dir):  # <-- Nuevo argumento
    """Genera la sección VAR para DB (basada en 'Static')."""
    scl_output = []
    static_vars = interface_data.get("Static", [])
    if static_vars:
        scl_output.append("VAR")
        # Pasar project_root_dir a generate_scl_declarations
        scl_output.extend(
            generate_scl_declarations(
                static_vars, indent_level=1, project_root_dir=project_root_dir
            )
        )  # <-- Pasar ruta raíz
        scl_output.append("END_VAR")
    else:
        print(
            "Advertencia: No se encontró sección 'Static' o está vacía en la interfaz del DB."
        )
        scl_output.append("VAR\nEND_VAR")  # Añadir vacío
    scl_output.append("")
    return scl_output


# Modificar generate_scl_for_db para aceptar y pasar project_root_dir
def generate_scl_for_db(data, project_root_dir):  # <-- Nuevo argumento
    """Genera el contenido SCL completo para un DATA_BLOCK."""
    scl_output = []
    scl_block_name = format_variable_name(data.get("block_name", "UnknownDB"))

    scl_output.extend(_generate_scl_header(data, scl_block_name))

    interface_data = data.get("interface", {})
    # Pasar project_root_dir a _generate_scl_interface
    scl_output.extend(
        _generate_scl_interface(interface_data, project_root_dir)
    )  # <-- Pasar ruta raíz

    scl_output.append("BEGIN")
    scl_output.append("  // Data Blocks have no executable code")
    scl_output.append("END_DATA_BLOCK")

    return scl_output
