import os
import json
import time
import subprocess
import shutil
from datetime import datetime
from zoneinfo import ZoneInfo
import concurrent.futures

import argparse
import json
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('-m', '--merge', help='The output to make custom')
parser.add_argument('-r', '--rem', help='The output to make custom')
args = parser.parse_args()
arg_val = args.file
out_val = args.output
rem_val = args.rem or 0
merge_val = args.merge or 0
error_retries_times = 0
# Set the timezone to "America/Monterrey"
os.environ['TZ'] = 'America/Monterrey'
tz=ZoneInfo("America/Monterrey")
os.system("")  # enables ansi escape characters in terminal
STOP_WHILE = False

CUSTOM_NAME_CODE = "perfumeria"

if arg_val:
  CUSTOM_NAME_CODE = arg_val
# Define color codes
RESET = "\033[0m"
BOLD = "\033[1m"
GREEN = "\033[92m"
RED = "\033[91m"
CYAN = "\033[96m"



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")
if rem_val:
  remove_dir_and_contents(f"results_{CUSTOM_NAME_CODE}")
# remove_dir_and_contents(f"{CUSTOM_NAME_CODE}")
os.makedirs(f"results_{CUSTOM_NAME_CODE}", exist_ok=True)
os.makedirs(f"{CUSTOM_NAME_CODE}", exist_ok=True)


def start_files(file_type='', index_step=1, start_index=0):
  # 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)

  # Function to parse the single-line cookie from the cookie.txt file
  def load_cookie_from_file(cookie_file):
    with open(cookie_file, "r") as f:
        line = f.readline().strip()
        if line.startswith("#"):
            parts = line.split("\t")
            if len(parts) >= 7:
                cookie_name = parts[5]
                cookie_value = parts[6]
                return {cookie_name: cookie_value}
    return {}

  # Load the single cookie from the cookie.txt file
  cookie_file = r'./cookie.txt'
  cookies = load_cookie_from_file(cookie_file)

  # Function to get results for a given index
  def get_results(i=0):
  
    if globals()["error_retries_times"] > 5:
      print("Sleeping due to many retries")
      time.sleep(20)
      globals()["error_retries_times"] = int(globals()["error_retries_times"]) - 1
      get_results(i)
      return 
    # 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]
        data["pasillo"] = data_list[i][3]
        # data["proveedor"] = data_list[i][3]
        data["pedir"] = 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}in {file_type}{RESET} {RED}{end_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET}")
            json.dump(data, f)
    except json.JSONDecodeError:
        globals()["error_retries_times"] =  globals()["error_retries_times"]+1
        print(f"Failed to parse JSON for index {i} , Retried? {globals()["error_retries_times"]}")
        

  # 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(1)  # Sleep for 1 second between requests

  return True

def merge_files(file_type = ''):
  stop = False
  data = []
  rol_zero = []
  rol_negative = []
  no_rol_negative = []
  real_list_rol = []
  list_zauto = []
  real_list = []
  falta_res = []
  # Directory containing the JSON files
  directory = f"results_{file_type}"

  # Process JSON files
  for i in range(13000):
    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
      ntest = curr["inventario"] <= curr["capacidadEmpaque"] and curr["resurtido"] != "SIN RESURTIDO" and curr["promedioLinea"] > 0.3
    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 norol:
        no_rol_negative.append(curr)
    if rol:
      real_list_rol.append(curr)
    if rol_zero_auto:
      list_zauto.append(curr)
    if ntest:
       falta_res.append(curr)
    if curr["inventario"] == 0 and curr["resurtido"]== "Automatico":
       falta_res.append(curr)
    real_list.append(curr)
    
  falta_res.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)
  with open(f"{file_type}/negatives.json", "w") as f:
      json.dump(rol_negative, 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}/faltantes.json", "w") as f:
      json.dump(falta_res, 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(custom_handler = "custom"):

  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=14) as executor:
    futures = [
      executor.submit(start_files, custom_handler, 13, 0),  # Even indices: 0, 2, 4...
      executor.submit(start_files, custom_handler, 13, 1),  # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 2),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 3),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 4),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 5),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 6),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 7),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 8),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 9),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 10),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 11),   # Odd indices: 1, 3, 5...
      executor.submit(start_files, custom_handler, 13, 12),   # Odd indices: 1, 3, 5...
    ]
    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}")

def is_time_to_stop():
    now = datetime.now(tz)
    return now.hour > 3 and now.minute > 0  and now.hour < 14 and now.minute < 59
Main_Loop = 0

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


master_data_list = []
with open(f"array/master_{CUSTOM_NAME_CODE}.json", "r") as f:
  master_data_list = json.load(f)

print(f"{count_files_in_folder(f"results_{CUSTOM_NAME_CODE}")}")
while True:
  if merge_val:
    print("Merging...")
    merge_files(f'{CUSTOM_NAME_CODE}')
    break
  if count_files_in_folder(f"results_{CUSTOM_NAME_CODE}") >= len(master_data_list):
    merge_files(f'{CUSTOM_NAME_CODE}')
    break
  else:
    run_tasks(f"{CUSTOM_NAME_CODE}")
