import os
import json
import time
import subprocess
import shutil
from datetime import datetime
from collections import defaultdict
import concurrent.futures
# Set the timezone to "America/Monterrey"
os.environ['TZ'] = 'America/Monterrey'
time.tzset()

STOP_WHILE = False

CUSTOM_NAME_CODE = "pedido"

# 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")

#remove_dir_and_contents(f"results_custom")
#os.makedirs(f"results_custom", exist_ok=True)
#os.makedirs(f"custom", 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):
    # 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:
        file_data = json.load(f)
        if "inventario" in file_data:
          print(f"{GREEN}File {file_path} already contains 'inventario'. Skipping...{RESET}")
          return

    # 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)

    # 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["pedir"]= data_list[i][3]
        # Write the data to the file
        with open(file_path, "w") as f:
            end_time = datetime.now()
            print(f"{GREEN}Done index {i},  Barcode: {data_list[i][1]}{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}")

  # 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 = []
  list_pedido = []
  # Directory containing the JSON files
  directory = f"results_{file_type}"
  grouped_items = defaultdict(list)
  # 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
      pedir = curr["pedir"]

    if int(curr["inventario"]) == 0 and rol:
        rol_zero.append(curr)
    elif int(curr["inventario"]) < 0 and rol:
        rol_negative.append(curr)
    elif int(curr["inventario"]) < 0 and norol:
        no_rol_negative.append(curr)
    elif rol:
      real_list_rol.append(curr)
    elif rol_zero_auto:
      list_zauto.append(curr)
      
    grouped_items[curr['categoria_real']].append(curr)
    
      
    real_list.append(curr)
  for categoria, group in grouped_items.items():
    group_data = defaultdict(list)
    group_data[group[0]["pedir"]].append(group)
    for cantidad, da in group_data.items():
      os.makedirs(f"{file_type}/{categoria}", exist_ok=True)
      with open(f"{file_type}/{categoria}/pedido_{cantidad}.json", "w") as f:
        json.dump(da, f, indent=2)
  # 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(list_zauto, f, indent=2)
  end_time = datetime.now()
  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()
  print(f"{CYAN}Started processing at {RESET}{RED}{start_time.strftime('%Y-%m-%d %H:%M:%S')}{RESET}")

  remove_dir_and_contents(f"results_{custom_handler}")
  os.makedirs(f"results_{custom_handler}", exist_ok=True)
  os.makedirs(f"{custom_handler}", exist_ok=True)


  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
      merge_files(f'{custom_handler}')
      

      # Copy "zero/" to "zero_old/
      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()
  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()
    return now.hour > 3 and now.minute > 0  and now.hour < 14 and now.minute < 59
Main_Loop = 0
while True:
  merge_files(f"{CUSTOM_NAME_CODE}")
  break
  Main_Loop = 1 + Main_Loop
  
  if is_time_to_stop():
    break 
  if Main_Loop < 2:
    #run_tasks(f"{CUSTOM_NAME_CODE}")
    break
  if Main_Loop > 2:
    break
  
