import os
import json
import time
import subprocess
import shutil
from datetime import datetime
from zoneinfo import ZoneInfo
import concurrent.futures
import pymysql
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='The file to make custom')
parser.add_argument('-o', '--output', help='The output to make custom')
parser.add_argument('-s', '--specific', help='The output to make custom')
parser.add_argument('-e', '--sortby', help='The output to make custom')
args = parser.parse_args()
arg_val = args.file
sort__by = args.sortby or "l"
out_val = args.output or 15
specific_val = args.specific or ""
STOP_WHILE = False
ADD_DATA1 = 1
# Define	 color codes
RESET = "\033[0m"

BOLD = "\033[1m"
GREEN = "\033[92m"
RED = "\033[91m"
CYAN = "\033[96m"
MASTER_FILE = "full_data"
if arg_val:
  MASTER_FILE = "full_data"
# Set the timezone to "America/Monterrey"
os.environ['TZ'] = 'America/Monterrey'
os.system("")  # enables ansi escape characters in terminal
tz=ZoneInfo("America/Monterrey")


def count_files_in_folder(folder_path):
    try:
        # List all items in the folder
        all_items = os.listdir(folder_path)
        
        # Count only the files
        file_count = sum(1 for item in all_items if os.path.isfile(os.path.join(folder_path, item)))
        
        return file_count
    except FileNotFoundError:
        return "The folder does not exist."
    except Exception as e:
        return f"An error occurred: {e}"

def add_data(code, descripcion, inv, cap, pend, fecha, marc, tp):

  try:
      # Establish a connection
      connection = pymysql.connect(
          host='localhost',
          user='root',
          password='',
          database='f9'
      )

      print("Connected to MySQL database")

      # Create a cursor object
      cursor = connection.cursor()
      cursor.execute(
          """
          INSERT INTO products (codigoBarras, descripcion, inventario, capacidadEmpaque, pendienteEntregaCabecera, pedidoPendiente, marca)
          VALUES (%s, %s, %s, %s, %s, %s, %s)
          """,
          (code, descripcion, inv, cap, pend, fecha, marc)
      )
      connection.commit()  
      print("Done:", cursor)

  except pymysql.MySQLError as e:
      print("Error while connecting to MySQL", e)
  finally:
      # Close the connection
      cursor.close()
      connection.close()
      print("MySQL connection is closed")

def remove_dir_and_contents(dir_path):
    if os.path.isdir(dir_path):
        shutil.rmtree(dir_path)
        print(f"Directory {dir_path} and all its contents removed successfully.")
    else:
        print(f"Directory {dir_path} does not exist or is not a directory.")
    
def copy_directory(src, dst):
    # Check if the source directory exists
    if os.path.exists(src):
        # If the destination directory exists, delete it first
        if os.path.exists(dst):
            shutil.rmtree(dst)  # Remove the destination directory and its contents
        shutil.copytree(src, dst)  # Copy the entire directory tree from src to dst
        print(f"Copied {src} to {dst}")
    else:
        print(f"Source directory {src} does not exist")

# remove_dir_and_contents(f"results_{MASTER_FILE}")
# remove_dir_and_contents(f"everything")
os.makedirs(f"results_{MASTER_FILE}", exist_ok=True)
os.makedirs(f"{MASTER_FILE}", exist_ok=True)
def start_files(file_type='', index_step=1, start_index=0):
  # Load the JSON list from the file
  def update_json_file(file_path, prov, pas):
    # Step 1: Read the JSON data
    with open(file_path, "r") as f:
        file_data = json.load(f)

    # Step 2: Update the data
    if "inventario" in file_data:
        # file_data["imagen"] = f'=IMAGEN("{image}")'
        file_data["proveedor"] = prov
        file_data["pasillo"] = pas
        file_data["pedir"] = 0
        with open(f"results_{file_type}/file_{i}.json", "w") as f:
            json.dump(file_data, f, indent=2)
            print("Updated")
  print(f"{GREEN}Starting  {file_type} at {index_step} in {start_index} {RESET}")
  with open(f"array/master_{file_type}.json", "r") as f:
    data_list = json.load(f)



  # Function to get results for a given index
  def get_results(i=0):
    # Check if the file exists and contains the 'inventario' field
    file_path = f"results_{file_type}/file_{i}.json"
    if os.path.exists(file_path):
      try:
        with open(file_path, "r") as f:
          file_data = json.load(f)
          if "inventario" in file_data:
            print(f"{GREEN}File {file_path} already contains 'inventario'. Skipping...{RESET}")
            # update_json_file(file_path, data_list[i][3], data_list[i][4])
            return
      except json.JSONDecodeError as e:
          print(f"JSON error: {e}")
      except UnicodeDecodeError as e:
          print(f"Encoding error: {e}")
    # Get the "codigo" from the list
    codigo = data_list[i][3]

    # Prepare the curl equivalent request using the subprocess
    curl_command = [
        'curl', '-k', '-s',
        '-A', 'Mozilla/5.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36',
        '-b', 'cookien.txt',
        f'https://www.intracomer.com.mx/simaEspecialWeb/AuditarServlet?_param=22&tipoReporte=2&codigo={codigo}'
    ]
    
    # Check if the result is valid JSON
    try:
        result = subprocess.run(curl_command, capture_output=True, text=True, encoding="utf-8")
        test = result.stdout
        data = json.loads(test)
        # data["seccion_numero"] = data_list[i][0]
        # data["categoria_real"] = data_list[i][2]
        # data["proveedor"] = data_list[i][4]
        # data["proveedor_num"] = data_list[i][3]
        # data["pasillo"] = data_list[i][4]
        # data["pedir"] = 1
        data["pedir"] = 1
        data["pasillo"] = 99
        data["seccion_numero"] = data_list[i][0]
        data["categoria_real"] = data_list[i][1]
        data["proveedor_num"] = data_list[i][2]
        data["proveedor"] = data_list[i][2]
        #data["image"] = f'=IMAGEN("{data_list[i][3]}")'
        # Write the data to the file
        with open(file_path, "w") as f:
            end_time = datetime.now(tz)
            print(f"{GREEN}Done index {i},  Barcode: {data_list[i][1]}{RESET}{RED}{end_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET} in {MASTER_FILE}")
            json.dump(data, f)
    except json.JSONDecodeError:
        print(f"Failed to parse JSON for index {i}")
    except UnicodeDecodeError as e:
        print(f"Encoding error: {e}, index: {i}")

  # Loop through the list, fetching results for every index with the given step
  for i in range(start_index, len(data_list), index_step):
    get_results(i)
    # time.sleep(0.5)
  return True

def merge_files(file_type = ''):
  stop = False
  data = []
  rol_zero = []
  rol_negative = []
  no_rol_negative = []
  real_list_rol = []
  list_zauto = []
  worry_some = []
  real_list = []
  new_pedido = []
  pedido_list = []
  venta_zero = []
  venta_zero2 = []
  nped = []
  nped2 = []
  nped3 = []
  invcap = []
  # Directory containing the JSON files
  directory = f"results_{file_type}"

  # Process JSON files
  for i in range(99999):
    file_path = os.path.join(directory, f"file_{i}.json")
    if os.path.exists(file_path):
      with open(file_path, "r") as f:
        arr = json.load(f)
        data.append(arr)
    else:
      continue
      
  pasillo_data = {}
  # Process the collected data
  for curr in data:
    if int(curr["inventario"]) == 0 and curr["resurtido"] == "Automatico":
        rol_zero.append(curr)
    if int(curr["inventario"]) < 0:
      rol_negative.append(curr)
    if int(curr["inventario"]) == 0 and curr["resurtido"] == "SIN RESURTIDO":
      continue
    # real_list.append(curr)
  for curr in data:
    real_list.append(curr)
  

  
  rol_negative.sort(key=lambda x: float(x.get("inventario", 0)), reverse=True)
  # Write the results to a JSON file
  with open(f"{file_type}/result.json", "w") as f:
      json.dump(real_list, f, indent=2)
  with open(f"{file_type}/rol_empty.json", "w") as f:
      json.dump(rol_zero, f, indent=2)
  with open(f"{file_type}/negatives.json", "w") as f:
      json.dump(rol_negative, f, indent=2)
  end_time = datetime.now(tz)
  print(f"{GREEN}for curr in data: Length: {RESET}{CYAN}{len(data)}{RESET}")
  print(f"{GREEN}real_list Length: {RESET}{CYAN}{len(real_list)}{RESET}")
  print(f"{CYAN}MERGED {file_type} at {RESET}{RED}{end_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET}")
  return True


# Main loop
def run_tasks(custom_handler = 'everything', futures_created=1):
    
  start_time = datetime.now(tz)
  print(f"{CYAN}Started processing at {RESET}{RED}{start_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET}")

    

  with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
    futures_list = []
    steps = 0
    for i in range(futures_created):
      if(i == 0):
        step = 0
      else:
        step = steps+i
      futures_list.append(executor.submit(start_files, custom_handler, futures_created, step))
    
    futures = futures_list
    done, not_done = concurrent.futures.wait(futures, return_when=concurrent.futures.ALL_COMPLETED)
    

    # Check when all futures are done
  if not not_done:  # If 'not_done' is empty, all tasks are done
      print("All futures are completed.")
  # Optionally process results if needed
  for future in done:
      try:
          result = future.result()  # Get the result of each future
          
      except Exception as exc:
          print(f"Task generated an exception: {exc}")
    # Wait for all tasks to complete
    
    # for future in concurrent.futures.as_completed(futures):
      # future.result()
  end_time = datetime.now(tz)
  print(f"{CYAN}Script finished at {RESET}{RED}{end_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET}")

Main_Loop = 0
master_data_list = []
with open(f"array/master_{MASTER_FILE}.json", "r") as f:
  master_data_list = json.load(f)
while True:
  # if count_files_in_folder(f"results_{MASTER_FILE}") >= len(master_data_list):
  merge_files(MASTER_FILE)
  break
  # else:
    # run_tasks(MASTER_FILE, int(out_val))
