import argparse
import json
from datetime import datetime
import os
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='The file to make custom')
parser.add_argument('-sf', '--subfolder', help='The output to make custom')
parser.add_argument('-o', '--output', help='The output to make custom')
parser.add_argument('-c', '--category', help='The output to make custom')
parser.add_argument('-m', '--marca', help='The output to make custom')
parser.add_argument('-t', '--tipo', help='The output to make custom')
parser.add_argument('-s', '--seccion', help='The output to make custom')
parser.add_argument('-p', '--pasillo', help='The output to make custom')
parser.add_argument('-i', '--inventario', help='The output to make custom')
parser.add_argument('-v', '--valor', help='The output to make custom')
parser.add_argument('-v2', '--valor2', help='The output to make custom')
parser.add_argument('-tf', '--transfer', help='The output to make custom')
parser.add_argument('-td', '--transferlookup', help='The output to make custom')
parser.add_argument('-data', '--data', help='The output to make custom')
parser.add_argument('-lt', '--last', help='The output to make custom')
args = parser.parse_args()
arg_val = args.file
sf_val = args.subfolder or ""
out_val = args.output 
category_val = args.category 
marca_val = args.marca
tipo_val = args.tipo
seccion_val = args.seccion
pasillo_val = args.pasillo
valor_val = args.valor
valor2_val = args.valor2 or 0
last_transfer_val = args.transfer
transfer_lookup_val = args.transferlookup
data_val = args.data or None # 0 is the normal fields array, 1 is the data from the array to not re make it
last_val = args.last or 3 # 0 is = today, 1 is = this Month, 2 is = 30 days, 3 is = this year, 4 is = last 30 days last year, 5 is last year
inv_val = args.inventario # 0 is = today, 1 is = this Month, 2 is = 30 days, 3 is = this year, 4 is = last 30 days last year, 5 is last year

file_name = ["zero_every_section/rol_empty.json"]
output_name = "master.json"
if arg_val:
  file_name = []
  file_name.append(arg_val)
  output_name = f"{sf_val}/{arg_val}"
#input_files = ["everything/faltantes.json"]
input_files = file_name
# Archivo a salir
if out_val:
  output_name = out_val
#output_file = "array/master_everything_pedido.json"
output_file = output_name
def get_date_str():
    """Returns the current date in 'dd-mm-YYYY' format."""
    return datetime.now().strftime('%d_%m_%Y')
def get_year_str():
    """Returns the current date in 'dd-mm-YYYY' format."""
    return datetime.now().strftime('%Y')
def get_month_str():
    """Returns the current date in 'dd-mm-YYYY' format."""
    return datetime.now().strftime('%m_%Y')

def get_lastyear_str():
    """Returns the current date in 'dd-mm-YYYY' format."""
    return datetime.now().replace(year=datetime.now().year - 1).strftime('%m_%Y')

def merge_json_files_to_custom_array(input_files, output_file, unique_key, fields):
    merged_data = {}
    sf_val = globals()["sf_val"] or ""
    if sf_val:
      sf_val = sf_val + "/"
    category_val = globals()["category_val"]
    marca_val = globals()["marca_val"]
    tipo_val = globals()["tipo_val"]
    seccion_val = globals()["seccion_val"]
    pasillo_val = globals()["pasillo_val"]
    valor_val = globals()["valor_val"]
    valor2_val = int(globals()["valor2_val"])
    last_transfer_val = globals()["last_transfer_val"]
    transfer_lookup_val = globals()["transfer_lookup_val"]
    data_val = globals()["data_val"]
    last_val = int(globals()["last_val"])
    inv_val = globals()["inv_val"]
    
    
    if data_val:
      if last_transfer_val:
        if not "/" in output_file and not sf_val:
          sf_val = last_transfer_val.replace("/", "_") + "/"
        if output_file == "result.json":
          output_file = "result_data.json"
      elif transfer_lookup_val:
        if not "/" in output_file and not sf_val:
          sf_val = transfer_lookup_val.replace("/", "_") + "/"
        if output_file == "result.json":
          output_file = "result_data.json"
      if last_val != 3:
        if last_val == 0:
          # if not "/" in output_file and not sf_val:
            sf_val = get_date_str() + "/"
        elif last_val == 1:
          # if not "/" in output_file and not sf_val:
            sf_val = get_month_str() + "/"
        elif last_val == 2:
          # if not "/" in output_file and not sf_val:
            sf_val = get_month_str() + "/"
          # if not output_file:
            output_file = f"30_days_{output_file}"
        elif last_val == 4:
          # if not "/" in output_file and not sf_val:
            sf_val = get_lastyear_str() + "/"
          # if not output_file:
            output_file = f"{get_date_str()}_{output_file}"
        elif last_val == 5:
          # if not "/" in output_file and not sf_val:
            sf_val = get_lastyear_str() + "/"
          # if not output_file:
            output_file = f"30_days_last_year_{output_file}"
      if not "/" in output_file:
        if not os.path.exists(sf_val):
          print("???")
          print(sf_val)
          os.makedirs(sf_val)
          
      if "/" in output_file:
        path_output = output_file.split("/")
        if len(path_output) == 2:
          if not os.path.exists(path_output[0]):
            os.makedirs(path_output[0])
          sf_val = path_output[0] + "/"
          output_file = path_output[1]
    # valor2_val = globals()["valor2_val"]
    # 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 = []
    custom_array2 = []
    custom_array3 = []
    custom_array4 = []
    print(category_val, marca_val, tipo_val, seccion_val, pasillo_val, last_transfer_val, transfer_lookup_val, valor_val, inv_val, data_val)
    conditions = [
        (category_val, lambda item: item["categoria_real"].replace(' ', '_').lower() == category_val),
        (marca_val, lambda item: item["marca"].replace(' ', '_').replace('-', '_').lower() == marca_val),
        (tipo_val, lambda item: item["resurtido"] == tipo_val),
        (seccion_val, lambda item: int(item.get("seccion_numero")) == int(seccion_val)),
        (pasillo_val, lambda item: int(item["pasillo"]) == int(pasillo_val)),
        (last_transfer_val, lambda item: (len(item["detalleTransferencias30Dias"])) > 0 and item["detalleTransferencias30Dias"][0]["tipoTransferencia"] == "POR CEDIS" and item["detalleTransferencias30Dias"][0]["fecha"] == last_transfer_val),
        (valor_val, lambda item: int(item["inventario"]) < int(valor_val)),
        (inv_val, lambda item: inv_val is not None and int(item["inventario"]) == int(inv_val))
    ]
    for item in merged_data.values():
      if not item.get("pedir", None):
        item["pedir"] = 1
      # item["descripcion"] = str(item.get("descripcion")).encode('utf-8')
      active_conditions = [cond for val, cond in conditions if val is not None]
      
      if all(cond(item) for cond in active_conditions):
        if not data_val:
          custom_entry2 = [item.get(field, None) for field in fields]
          custom_array2.append(custom_entry2)
        else:
          custom_array2.append(item)
      # print(custom_array2)
      # 0 is = today, 1 is = this Month, 2 is = 30 days, 3 is = this year, 4 is = last year last 30 days, 5 is = last year
      if last_val == 0 and item["ventas"]["ventasDiaCorriente"] < valor2_val:
        custom_array4.append(item)
      elif last_val == 1 and item["ventas"]["ventasMesCorriente"] < int(valor2_val):
        custom_array4.append(item)
      elif last_val == 2 and item["ventas"]["ventasUltimos30diasAnioCorriente"] < valor2_val:
        custom_array4.append(item)
      elif last_val == 4 and item["ventas"]["ventasUltimos30diasAnioAnterior"] < valor2_val:
        custom_array4.append(item)
      elif last_val == 5 and item["ventas"]["acumuladoAnualAnioAnterior"] < valor2_val:
        custom_array4.append(item)
      if transfer_lookup_val:
        
        allTransfers = item["detalleTransferencias30Dias"]
        
        for field in allTransfers:
          
          if str(field.get("fecha")) == transfer_lookup_val :
            if not data_val:
              custom_entry3 = [item.get(field, None) for field in fields]
              custom_array3.append(custom_entry3)
            else:
              custom_array3.append(item)
              
      if len(custom_array2) == 0 and len(custom_array3) == 0 and len(custom_array4) == 0:
        if not data_val:
          custom_entry = [item.get(field, None) for field in fields]
          custom_array.append(custom_entry)
        else:
          custom_array.append(item)
      else:
        custom_array = []
    # print(custom_array)
    if len(custom_array2) > 0 and len(custom_array3) == 0:
      print(sf_val, "XD", output_file)
      with open(f"{sf_val}{output_file}", 'w', encoding='utf-8') as f:
        print(f"eee  {sf_val}{output_file}")
        json.dump(custom_array2, f, ensure_ascii=True, indent=4)

      print(f"assad to {output_file}")
    # Write custom array to the output file
    elif len(custom_array3) > 0 :
      with open(f"{sf_val}{output_file}", 'w', encoding='utf-8') as f:
          json.dump(custom_array3, f, ensure_ascii=True, indent=4)
    elif len(custom_array4) > 0:
      with open(f"{sf_val}{output_file}", 'w', encoding='utf-8') as f:
          json.dump(custom_array4, f, ensure_ascii=True, indent=4)
    else:
      if(data_val):
        out_custom = "custom_"
        output_file = f"{out_custom}{output_file}"
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(custom_array, f, ensure_ascii=True, indent=4)
    print(f"Custom1 Length: {len(custom_array)} - Custom2 Length: {len(custom_array2)} - Custom3 Length: {len(custom_array3)} - Custom4 Length: {len(custom_array4)}, sf_val :: {sf_val}")
    print(f"xd {last_val}")
    print(f"Merge completed. Custom array saved to {output_file}")

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
if arg_val:
  # Run the function
  
  merge_json_files_to_custom_array(input_files, output_file, unique_key, fields)
else:
  print("XD")
  print(get_lastyear_str())
  # for i in range(35):
      # file_path = f"everything/pasillo_{i}"
      # if os.path.exists(file_path):
        # f = [f"{file_path}/result.json"]
        # o = f"array/master_pasillo_{i}.json"
        # merge_json_files_to_custom_array(f, o, unique_key, fields)

      # else:
        # continue

