import os
import re
import pandas as pd

# 1. Cargar la retícula 10k desde el Excel
df_10k = pd.read_excel("10k_EPSG25830.xls")

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

renamed_count = 0
unmatched_count = 0

for path in filepaths:
    # Extraer la carpeta H50 y las coordenadas XXX-YYYY del nombre del archivo
    match = re.search(
        r"(H50_\d+)[\\/].*?CYL_(\d+)-(\d+)\.laz$", path, re.IGNORECASE
    )
    if not match:
        continue

    h50_folder, x_km, y_km = match.groups()
    h50_num = h50_folder.split("_")[1]  # Ej: "0055"

    x = int(x_km) * 1000
    y = int(y_km) * 1000

    # Esquina superior izquierda (X, Y) -> Centro de la tesela (X + 500, Y - 500)
    cx, cy = x + 500, y - 500

    # Buscar hojas 10k que contengan el centro de la tesela
    sheets = df_10k[
        (df_10k["Xmin"] <= cx)
        & (df_10k["Xmax"] >= cx)
        & (df_10k["Ymin"] <= cy)
        & (df_10k["Ymax"] >= cy)
    ]["Hoja_10k"].tolist()

    # Si hay solape en bordes, priorizamos la hoja referente al bloque H50 actual
    sheet_name = None
    if len(sheets) == 1:
        sheet_name = sheets[0]
    elif len(sheets) > 1:
        filtered = [s for s in sheets if s.startswith(h50_num)]
        sheet_name = filtered[0] if filtered else sheets[0]
    else:
        # Si cae justo fuera del límite, buscar la hoja 10k más cercana
        dx = (
            pd.concat([df_10k["Xmin"] - cx, cx - df_10k["Xmax"]], axis=1)
            .max(axis=1)
            .clip(lower=0)
        )
        dy = (
            pd.concat([df_10k["Ymin"] - cy, cy - df_10k["Ymax"]], axis=1)
            .max(axis=1)
            .clip(lower=0)
        )
        dist = (dx**2 + dy**2) ** 0.5
        sheet_name = df_10k.loc[dist.idxmin(), "Hoja_10k"]

    # Construir el nuevo nombre de archivo
    directory, old_filename = os.path.split(path)
    new_filename = (
        f"PNOA_LIDAR_2025_CyL_H10_{sheet_name}_{x_km}-{y_km}_NPC01.laz"
    )
    new_path = os.path.join(directory, new_filename)

    # Renombrar archivo si existe en disco
    if os.path.exists(path):
        os.rename(path, new_path)
        renamed_count += 1
    else:
        print(f"Generado mapeo: {old_filename} -> {new_filename}")

print(f"\nProceso finalizado. Archivos procesados: {len(filepaths)}")