#  *
#  * Debug de ots_xml_to_json.py (sin llamadas remotas)
#  *
#  * @author: Marc Henales
#  * @version: 1.0
#  * @created: 17/03/2026
#  *

import os
import xml.etree.ElementTree as ET
import json
import shutil
import datetime

#* Ruta de la carpeta que contiene los archivos XML
carpeta = './temp'

print(f"[DEBUG] Carpeta de entrada: {os.path.abspath(carpeta)}")
print(f"[DEBUG] ¿Carpeta existe? {os.path.exists(carpeta)}")
if os.path.exists(carpeta):
    archivos_xml = [f for f in os.listdir(carpeta) if f.endswith('.xml')]
    print(f"[DEBUG] Archivos XML encontrados: {archivos_xml}")
print()

#* Función para simplificar XML a JSON
def xml_to_json(element, include_ns=False, depth=0):
    indent = "  " * depth
    print(f"[DEBUG] {indent}Procesando elemento: <{element.tag.split('}')[-1]}>")

    json_dict = {}

    #* Manejar atributos del elemento
    if element.attrib:
        print(f"[DEBUG] {indent}  Atributos: {element.attrib}")
        json_dict.update({"" + k + "": v for k, v in element.attrib.items()})

    #* Capturar contenido de texto si existe
    if element.text and element.text.strip():
        print(f"[DEBUG] {indent}  Texto: {element.text.strip()}")
        json_dict["#*text"] = element.text.strip()

    #* Iterar sobre los hijos del elemento
    for child in element:
        tag = child.tag if include_ns else child.tag.split('}')[-1]
        value = xml_to_json(child, include_ns, depth + 1)

        #* Manejar elementos duplicados como listas
        if tag in json_dict:
            if not isinstance(json_dict[tag], list):
                print(f"[DEBUG] {indent}  Convirtiendo '{tag}' a lista (elemento duplicado)")
                json_dict[tag] = [json_dict[tag]]
            json_dict[tag].append(value)
        else:
            json_dict[tag] = value

    return json_dict


#* Función para procesar cada archivo XML
def procesar_xml(archivo):
    print(f"\n{'='*60}")
    print(f"[DEBUG] Procesando archivo: {archivo}")
    print(f"{'='*60}")

    try:
        tree = ET.parse(archivo)
        root = tree.getroot()
        print(f"[DEBUG] XML parseado correctamente. Elemento raíz: <{root.tag.split('}')[-1]}>")

        #* Convertir XML a JSON
        print(f"\n[DEBUG] --- Iniciando conversión XML -> JSON ---")
        json_data = xml_to_json(root)
        print(f"[DEBUG] --- Conversión completada ---\n")

        #* Extraer el ID único de la reserva
        unique_id = None
        for elem in root.iter():
            if 'UniqueID' in elem.tag:
                unique_id = elem.attrib.get('ID')
                print(f"[DEBUG] UniqueID encontrado: {unique_id} (en etiqueta: {elem.tag})")
                break

        if unique_id is None:
            print(f"[DEBUG] AVISO: No se encontró UniqueID en el XML")
        else:
            json_data['UniqueID'] = unique_id

        #* Datos XML
        archivo_xml = archivo
        nombre_xml = os.path.basename(archivo_xml)
        print(f"\n[DEBUG] Nombre original del archivo XML: {nombre_xml}")

        if "MODIFICATION" in nombre_xml:
            nombre_xml = "MODIFICATION.xml"
        elif "NEW" in nombre_xml:
            nombre_xml = "NEW.xml"
        else:
            nombre_xml = "CANCELLATION.xml"
        print(f"[DEBUG] Nombre normalizado XML: {nombre_xml}")

        #* Datos JSON
        archivo_json = os.path.splitext(archivo)[0] + '.json'
        nombre_json = os.path.basename(archivo_json)
        print(f"[DEBUG] Nombre original del archivo JSON: {nombre_json}")

        if "MODIFICATION" in nombre_json:
            nombre_json = "MODIFICATION.json"
        elif "NEW" in nombre_json:
            nombre_json = "NEW.json"
        else:
            nombre_json = "CANCELLATION.json"
        print(f"[DEBUG] Nombre normalizado JSON: {nombre_json}")

        #* Guardo Año/Mes (currentDate)
        year = datetime.datetime.strftime(datetime.datetime.now(), '%Y')
        month = datetime.datetime.strftime(datetime.datetime.now(), '%m')
        print(f"\n[DEBUG] Fecha actual -> Año: {year}, Mes: {month}")

        #* Construir rutas de destino
        if unique_id:
            destino_json = os.path.join("./json", year, month, unique_id + "_" + nombre_json)
            destino_xml  = os.path.join("./xml",  year, month, unique_id + "_" + nombre_xml)
        else:
            destino_json = os.path.join("./json", year, month, nombre_json)
            destino_xml  = os.path.join("./xml",  year, month, nombre_xml)

        print(f"[DEBUG] Ruta destino JSON: {destino_json}")
        print(f"[DEBUG] Ruta destino XML:  {destino_xml}")

        #* Simular carpetas de destino (sin crearlas)
        dir_json = os.path.dirname(destino_json)
        dir_xml  = os.path.dirname(destino_xml)
        print(f"\n[DEBUG] [SIMULADO] os.makedirs('{dir_json}', exist_ok=True)")
        print(f"[DEBUG] [SIMULADO] os.makedirs('{dir_xml}', exist_ok=True)")

        #* Mostrar JSON resultante
        json_data_str = json.dumps(json_data, indent=4)
        print(f"\n[DEBUG] JSON generado:")
        print(json_data_str)

        #* Simular petición POST (sin enviarla)
        url = 'http://10.11.200.153/ghot/booking_notification_ots'
        file_param = (unique_id + "_" + nombre_json) if unique_id else nombre_json
        data = {
            'test': 0,
            'file': file_param,
            'json': json.dumps(json_data)
        }
        print(f"\n[DEBUG] [SIMULADO] POST {url}")
        print(f"[DEBUG] Parámetros que se enviarían:")
        print(f"  test : {data['test']}")
        print(f"  file : {data['file']}")
        print(f"  json : (ver JSON generado arriba)")

        #* Simular respuesta exitosa (response.text == "1")
        simulated_response_status = 200
        simulated_response_text   = "1"
        print(f"\n[DEBUG] [SIMULADO] Respuesta HTTP: {simulated_response_status}")
        print(f"[DEBUG] [SIMULADO] Cuerpo respuesta: \"{simulated_response_text}\"")

        if simulated_response_status == 200 and simulated_response_text == "1":
            print(f"\n[DEBUG] [SIMULADO] Guardaría JSON en: {archivo_json}")
            print(f"[DEBUG] [SIMULADO] shutil.move('{archivo_json}', '{destino_json}')")
            print(f"[DEBUG] [SIMULADO] shutil.move('{archivo_xml}', '{destino_xml}')")
            print(f"[DEBUG] Flujo completado con éxito para: {archivo}")
        else:
            print(f"[DEBUG] Error simulado: respuesta inesperada")

    except ET.ParseError as e:
        print(f"[DEBUG] ERROR al parsear XML '{archivo}': {e}")
    except Exception as e:
        print(f"[DEBUG] ERROR inesperado procesando '{archivo}': {e}")


#* Recorrer todos los archivos en la carpeta
if not os.path.exists(carpeta):
    print(f"[DEBUG] ERROR: La carpeta '{carpeta}' no existe. Crea la carpeta y añade archivos XML.")
else:
    xml_files = [f for f in os.listdir(carpeta) if f.endswith('.xml')]
    if not xml_files:
        print(f"[DEBUG] No se encontraron archivos .xml en '{carpeta}'.")
    else:
        for nombre_archivo in xml_files:
            ruta_archivo = os.path.join(carpeta, nombre_archivo)
            procesar_xml(ruta_archivo)

print(f"\n[DEBUG] Fin del proceso.")
