import json
import glob
import os

def createMaster(file_type ='abarr'):
  # Load the JSON data from result.json
  if(file_type == 'abarr'):
    return

  with open(f'{file_type}/result.json', 'r') as f:
      data = json.load(f)

  # Filter the objects where 'resurtido' equals 'Automatic' and 'inventario' equals 0
  rol_empty = [
      [item.get('seccion_numero'), item.get('codigoBarras'), item.get('categoria_real')]
      for item in data
      if item.get('resurtido') == "Automatico" and item.get('inventario') < 5
  ]

  # Save the filtered objects to array_zero_gourmet.json
  with open(f'new_zero_{file_type}.json', 'w') as f:
      json.dump(data, f, indent=4)
  print(f"File 'master_zero_{file_type}.json' created successfully.length: {len(data)}")

def combine_all_files():
    # List to hold data from all array_zero_*.json files
    combined_data = []

    # Find all files matching the pattern 'array_zero_*.json'
    for file_name in glob.glob("new_zero_*.json"):
        with open(file_name, 'r') as f:
            data = json.load(f)
            combined_data.extend(data)  # Append data to combined list

    # Save combined data into one file
    with open("array_all_combined.json", "w") as f:
        json.dump(combined_data, f, indent=4)
    combined_file = "array_all_combined.json"
    print(f"File 'array_all_combined.json' created successfully. length: {len(combined_data)}")
    for file_name in glob.glob("new_zero_*.json"):
         if file_name != combined_file:
            os.remove(file_name)
            print(f"Deleted '{file_name}'")


createMaster('abarrotes')
createMaster('gourmet')
createMaster('cava')
createMaster('marca_propia')
createMaster('perfumeria')
combine_all_files()
