# -*- coding: utf-8 -*-

"""
Script: ExportGvlToCsv.py
Version / Versão: 1.0.0.0
Created on / Data de criação: 2025-08-01
Description / Descrição:
    EN: Exports the textual declaration of a GVL to a CSV file.
    PT: Exporta a declaração textual de uma GVL para um arquivo CSV.

Changelog / Histórico de versões:
    - 1.0.0.0:
        EN: Initial version.
        PT: Versão inicial.
"""

import scriptengine
import csv
import os

def ExportGvlToCsv(GVL_name, FilePath):
    """
    Export the textual declaration of a GVL to a CSV file containing:
    - Variable scope (e.g., VAR_GLOBAL, VAR_INPUT, etc.)
    - Variable declaration line (name and type)
    - Inline comment, if present

    Exporta a declaração textual de uma GVL para um arquivo CSV contendo:
    - Escopo da variável (ex.: VAR_GLOBAL, VAR_INPUT etc.)
    - Declaração da variável (nome e tipo)
    - Comentário inline, se houver

    Parameters / Parâmetros:
    - GVL_name (str): Name of the GVL to export / Nome da GVL a ser exportada
    - FilePath (str): Full path to the output CSV file / Caminho completo do arquivo CSV
    """

    # Ensure the directory exists / Garante que o diretório existe
    folder = os.path.dirname(FilePath)
    if not os.path.exists(folder):
        try:
            os.makedirs(folder)
            print("[Info] Folder created: {}".format(folder))
            print("[Info] Pasta criada: {}".format(folder))
            scriptengine.system.ui.info("[Info] Pasta criada: {}".format(folder))
        except Exception as e:        
            print("[Error] Failed to create folder: {}".format(str(e)))
            print("[Erro] Falha ao criar a pasta: {}".format(str(e)))
            scriptengine.system.ui.error("[Erro] Falha ao criar a pasta: {}".format(str(e)))
            return

    # Access the active project / Acessa o projeto ativo
    proj = scriptengine.projects.primary

    # Try to find the GVL object by name / Tenta encontrar o objeto GVL pelo nome
    result = proj.find(GVL_name, recursive=True)
    if not result:
        print("[Error] GVL '{}' not found in the project.".format(GVL_name))
        print("[Erro] GVL '{}' não encontrada no projeto.".format(GVL_name))
        scriptengine.system.ui.error("Não foi possível encontrar a GVL indicada!")
        return

    obj = result[0]

    # Read the textual declaration of the GVL / Lê a declaração textual da GVL
    lines = obj.textual_declaration.text.splitlines()

    variables = []        # List of parsed variable entries / Lista de variáveis extraídas
    current_scope = None  # Tracks the active VAR_ scope (e.g., VAR_GLOBAL)

    for line in lines:
        line = line.strip()
        if line.startswith("VAR_"):
            current_scope = line  # Save the scope header / Armazena o escopo
        elif line.startswith("END_VAR"):
            current_scope = None  # End of scope block / Fim do bloco
        elif current_scope and ':' in line:
            # Separate code from inline comment / Separa código do comentário inline
            parts = line.split("//", 1)
            code = parts[0].strip()
            comment = parts[1].strip() if len(parts) > 1 else ""
            if code:
                variables.append({
                    "Scope": current_scope,
                    "Name": code,
                    "Comment": comment
                })

    try:
        # Write CSV file / Grava o arquivo CSV
        with open(FilePath, mode='wb') as csvfile:  # mode='wb' required by MasterTool script engine
            writer = csv.DictWriter(csvfile, fieldnames=["Scope", "Name", "Comment"], delimiter=';')
            writer.writeheader()
            for var in variables:
                writer.writerow(var)
        print("[Success] GVL exported to: {}".format(FilePath))
        print("[Sucesso] GVL exportada para: {}".format(FilePath))
        scriptengine.system.ui.info("[Sucesso] GVL exportada para: {}".format(FilePath))
    except Exception as e:
        print("[Error] Failed to write CSV file: {}".format(str(e)))
        print("[Erro] Falha ao escrever o arquivo CSV: {}".format(str(e)))
        scriptengine.system.ui.error("[Erro] Falha ao escrever o arquivo CSV: {}".format(str(e)))

try:
    resultado = PromptResult.No

    while resultado != PromptResult.Yes and resultado != PromptResult.Cancel:    
        gvl_name = scriptengine.system.ui.query_string("Digite o nome da GVL: ", "", "")
        gvl_location = scriptengine.system.ui.query_string("Digite o caminho para exportar a GVL: ", "C:\\temp\GVL_Exported.csv", "")

        resultado = scriptengine.system.ui.prompt("Os valores abaixo estão corretos? \n\nNome da GVL: " + gvl_name + " \nCaminho: " + gvl_location, PromptChoice.YesNoCancel, PromptResult.Cancel) # Prompt - Options
except Exception as e:
    scriptengine.system.ui.error("Erro durante entrada de valores!")

if resultado == PromptResult.Yes:
    ExportGvlToCsv(gvl_name, gvl_location)
