import os
import shutil
from datetime import datetime

def mover_archivos(nombre_archivo):
    # Directorio desde donde se ejecuta Python
    base = os.getcwd()

    # Carpeta xml relativa al directorio actual
    base_xml = os.path.join(base, "xml")
    base_json = os.path.join(base, "json")

    hoy = datetime.now()
    year = hoy.strftime("%Y")
    month = hoy.strftime("%m")

    destino_dir_xml = os.path.join(base_xml, year, month)
    os.makedirs(destino_dir_xml, exist_ok=True)

    for root, dirs, files in os.walk(base_xml):
        for file in files:
            if file.strip().lower() == nombre_archivo.lower():
                origen = os.path.join(root, file)

                # Evitar mover si ya está en destino
                if os.path.abspath(root) == os.path.abspath(destino_dir_xml):
                    continue

                destino = os.path.join(destino_dir_xml, file)

                if os.path.exists(destino):
                    print(f"⚠️ Ya existe: {destino}")
                    continue

                shutil.move(origen, destino)
                print(f"✅ Movido: {origen} → {destino}")
        
    # Movemos JSON
    destino_dir_json = os.path.join(base_json, year, month)
    os.makedirs(destino_dir_json, exist_ok=True)
    for root, dirs, files in os.walk(base_json):
        for file in files:
            if file.strip().lower() == nombre_archivo.lower().replace('.xml', '.json'):
                origen = os.path.join(root, file)

                # Evitar mover si ya está en destino
                if os.path.abspath(root) == os.path.abspath(destino_dir_json):
                    continue

                destino = os.path.join(destino_dir_json, file)

                if os.path.exists(destino):
                    print(f"⚠️ Ya existe: {destino}")
                    continue

                shutil.move(origen, destino)
                print(f"✅ Movido: {origen} → {destino}")

# Uso
import sys

if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(1)

    mover_archivos(sys.argv[1])
