import os
import re
import pandas as pd

# 1. Cargar el Excel de retículas MTN5000
excel_path = "5k_EPSG25830.xls"
df_5k = pd.read_excel(excel_path)

# Extraer matrices para optimizar la búsqueda espacial
x_min = df_5k["Xmin"].values
x_max = df_5k["Xmax"].values
y_min = df_5k["Ymin"].values
y_max = df_5k["Ymax"].values
h05_names = df_5k["H05"].astype(str).values


def get_h05_sheet(cx, cy):
    """Devuelve la hoja 5000 cuyo recinto contiene al punto (cx, cy)."""
    mask = (x_min <= cx) & (cx <= x_max) & (y_min <= cy) & (cy <= y_max)
    matches = h05_names[mask]
    return matches[0] if len(matches) > 0 else None


# 2. Leer la lista de archivos
listado_path = "listadofiles.txt"
with open(listado_path, "r", encoding="utf-8") as f:
    filepaths = [line.strip() for line in f if line.strip()]

# Regex para extraer las coordenadas XXX y YYYY del nombre actual
# Ejemplo entrada: PNOA_LIDAR_2025_CyL_H10_0055_1-4_328-4782_NPC01.laz
pattern = re.compile(r"_(\d{3})-(\d{4})_NPC01\.laz", re.IGNORECASE)

renamed_count = 0
not_found_count = 0

print("Iniciando proceso de renombrado...")

for path in filepaths:
    if not os.path.exists(path):
        # Si la ruta no está accesible en este equipo, salta la iteración
        continue

    directory, old_filename = os.path.split(path)
    match = pattern.search(old_filename)

    if match:
        xxx_str, yyyy_str = match.groups()
        xxx = int(xxx_str)
        yyyy = int(yyyy_str)

        # Esquina superior izquierda en metros: X = xxx * 1000, Y = yyyy * 1000
        # Centroide de la tesela de 1000m x 1000m:
        cx = xxx * 1000 + 500
        cy = yyyy * 1000 - 500

        h05_code = get_h05_sheet(cx, cy)

        if h05_code:
            # Formato de salida: PNOA-LIDAR-2025-CyL_H05-????_?-?_XXX-YYYY_NPC01.laz
            new_filename = f"PNOA-LIDAR-2025-CyL_H05-{h05_code}_{xxx_str}-{yyyy_str}_NPC01.laz"
            new_path = os.path.join(directory, new_filename)

            # Renombrar archivo en disco
            os.rename(path, new_path)
            renamed_count += 1
        else:
            print(f"[Aviso] No se encontró hoja 5k para el centroide ({cx}, {cy}): {old_filename}")
            not_found_count += 1

print(f"\nProceso finalizado. Archivos renombrados: {renamed_count}. No encontrados: {not_found_count}.")