import os
import json
import time
import subprocess
import shutil
from datetime import datetime
from zoneinfo import ZoneInfo
import concurrent.futures
# Set the timezone to "America/Monterrey"
os.environ['TZ'] = 'America/Monterrey'
os.system("")  # enables ansi escape characters in terminal
tz=ZoneInfo("America/Monterrey")
STOP_WHILE = False
# Define color codes
RESET = "\033[0m"
BOLD = "\033[1m"
GREEN = "\033[92m"
RED = "\033[91m"
CYAN = "\033[96m"
MASTER_FILE = ["cava", "gourmet"]
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_gourmet")
remove_dir_and_contents(f"results_cava")


# remove_dir_and_contents("gourmet")
# remove_dir_and_contents("cava")



os.makedirs(f"results_gourmet", exist_ok=True)
os.makedirs(f"results_cava", exist_ok=True)


os.makedirs(f"gourmet", exist_ok=True)
os.makedirs(f"cava", exist_ok=True)


def start_files(file_type='', index_step=1, start_index=0):

  def update_json_file(file_path, categoria_real_value):
    # 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["categoria_real"] = categoria_real_value
    
    # Step 3: Write the updated data back to the file
    with open(file_path, "w") as f:
        json.dump(file_data, f, indent=4)  # Optional: indent for readability

  # Load the JSON list from the file

  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)

  # Load the single cookie from the cookie.txt file
  cookie_file = r'./cookien.txt'

  # 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):
      with open(file_path, "r") as f:
        try:
          file_data = json.load(f)
          if "inventario" in file_data:
            print(f"{GREEN}File {file_path} already contains 'inventario'. Skipping...{RESET}")
          return
        except json.JSONDecodeError:
          print(f"Failed to parse JSON for index {i}")

    # Get the "codigo" from the list
    codigo = data_list[i][1]

    # 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}'
    ]
    result = subprocess.run(curl_command, capture_output=True, text=True, encoding="utf-8")

    # Check if the result is valid JSON
    try:
        data = json.loads(result.stdout)
        data["seccion_numero"] = data_list[i][0]
        data["categoria_real"] = data_list[i][2]
        # 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}in {file_type}{RESET} {RED}{end_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET}")
            json.dump(data, f)
    except json.JSONDecodeError:
        print(f"Failed to parse JSON for index {i} {RED} in {file_type}{RESET} Retrying...")
        # time.sleept(0.1)
        # get_results(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)
  return True

def merge_files(file_type = ''):
  stop = False
  data = []
  rol_zero = []
  rol_negative = []
  no_rol_negative = []
  real_list_rol = []
  list_zauto = []
  real_list = []
  ntest = []
  end_time = datetime.now(tz)
  # 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

  # Process the collected data
  for curr in data:
    if curr is not None and "resurtido" in curr and "inventario" in curr:
      rol = curr["resurtido"] != "SIN RESURTIDO"
      norol = curr["resurtido"] == "SIN RESURTIDO"
      rol_zero_auto = curr["resurtido"] == "Automatico" and curr["inventario"] == 0
    
    if int(curr["inventario"]) == 0 and curr["resurtido"] == "Automatico":
        rol_zero.append(curr)
    elif int(curr["inventario"]) < 0 and norol:
        no_rol_negative.append(curr)
    elif rol:
      real_list_rol.append(curr)

    if int(curr["inventario"]) < 0:
      rol_negative.append(curr)
    if int(curr["inventario"]) < int(curr["capacidadEmpaque"]) and curr["resurtido"] == "Automatico" and curr["promedioLinea"] > 0.3:
      ntest.append(curr)
    if int(curr["inventario"]) < (int(curr["capacidadEmpaque"]) * 4) and curr["resurtido"] == "Automatico" and curr["promedioLinea"] > 1:
      ntest.append(curr)
    real_list.append(curr)
    
  ntest.sort(key=lambda x: float(x.get("promedioLinea", 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)

  # Write the results to a JSON fil
  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)
  with open(f"{file_type}/faltantes.json", "w") as f:
      json.dump(ntest, f, indent=2)
  end_time = datetime.now(tz)
  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():
    
  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=18) as executor:
    futures = [
      executor.submit(start_files, 'gourmet', 8, 0), 
      executor.submit(start_files, 'gourmet', 8, 1), 
      executor.submit(start_files, 'gourmet', 8, 2), 
      executor.submit(start_files, 'gourmet', 8, 3), 
      executor.submit(start_files, 'gourmet', 8, 4), 
      executor.submit(start_files, 'gourmet', 8, 5), 
      executor.submit(start_files, 'gourmet', 8, 6), 
      executor.submit(start_files, 'gourmet', 8, 7), 

      executor.submit(start_files, 'cava', 8, 0), 
      executor.submit(start_files, 'cava', 8, 1), 
      executor.submit(start_files, 'cava', 8, 2), 
      executor.submit(start_files, 'cava', 8, 3), 
      executor.submit(start_files, 'cava', 8, 4), 
      executor.submit(start_files, 'cava', 8, 5), 
      executor.submit(start_files, 'cava', 8, 6), 
      executor.submit(start_files, 'cava', 8, 7),
    ]
    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
      merge_files('gourmet')
      merge_files('cava')
      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}")

STOP_WHILE = False
def merge_all():
    merge_files('abarrotes')

def is_time_to_stop():
    now = datetime.now(tz)
    globals()["STOP_WHILE"] = True
    return now.hour > 12 and now.minute > 50 and now.hour < 3 and now.minute < 59
def is_time_to_run():
    now = datetime.now(tz)
    return now.hour > 3 and now.minute > 0 and now.hour < 15 and now.minute < 59

COUNT_DOWN = 0
master_data_list1 = []
with open(f"array/master_{MASTER_FILE[0]}.json", "r") as f:
  master_data_list1 = json.load(f)
master_data_list2 = []
with open(f"array/master_{MASTER_FILE[1]}.json", "r") as f:
  master_data_list2 = json.load(f)

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}"

while True:
  if count_files_in_folder(f"results_{MASTER_FILE[0]}") >= len(master_data_list1) and count_files_in_folder(f"results_{MASTER_FILE[1]}") >= len(master_data_list2):
    break
  else:
    run_tasks()
