import json
import os
from datetime import datetime

    # Generate output file name with current date
def get_date_str():
    """Returns the current date in 'dd-mm-YYYY' format."""
    return datetime.now().strftime('%d_%m_%Y')
current_date_str = get_date_str()
current_path = os.getcwd()
current_dir_path = os.path.basename(current_path)

def merge_json_files_to_custom_array(input_files, output_file, unique_key, fields):
    merged_data = {}
    
    # Load and merge data from input files
    for file in input_files:
        with open(file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            for item in data:
                key = item.get(unique_key)
                if key:  # Ensure the key exists
                    merged_data[key] = item
    
    # Create the custom array
    custom_array = []
    for item in merged_data.values():
        custom_entry = [item.get(field, None) for field in fields]
        custom_array.append(custom_entry)
    
    # Write custom array to the output file
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(custom_array, f, ensure_ascii=False, indent=2)
    print(f"Merge completed. Custom array saved to {output_file}")

# Define your input files, output file, unique key, and desired fields
input_files = ["result.json"]
output_file = f"../array/master_{current_dir_path}.json"
unique_key = "codigoBarras"  # Replace with the unique key in your JSON
fields = ["seccion_numero", "codigoBarras", "categoria_real", "proveedor_num", "pasillo", "pedir", "proveedor_num"]  # Desired fields


# Run the function
merge_json_files_to_custom_array(input_files, output_file, unique_key, fields)
