import os
import subprocess
import glob

# --- RUTAS DE TRABAJO ---
directorio_tifs = r"P:\Cartografia\02_Altimetria\023_LIDAR\estad"
lista_archivos_txt = os.path.join(directorio_tifs, "lista_tifs_0341.txt")
archivo_vrt = os.path.join(directorio_tifs, "mosaico_0341.vrt")
archivo_salida = os.path.join(directorio_tifs, "0341.IMG")

# --- PARÁMETROS ESPACIALES ---
epsg = "EPSG:25830"
resolucion = "10 10"
valor_nodata = "-9999"

# Orden para -projwin: X_min (ulx), Y_max (uly), X_max (lrx), Y_min (lry)
projwin = ["290080", "4634400", "318410", "4615020"]

# 1. Localizar los TIFs de 68 bandas generados
print("Localizando archivos *_Estadisticas.tif...")
archivos_tif = glob.glob(os.path.join(directorio_tifs, "*_Estadisticas.tif"))

if not archivos_tif:
    print("ERROR: No se encontraron archivos *_Estadisticas.tif en la carpeta 'estad'.")
    exit()

print(f"Se han localizado {len(archivos_tif)} archivos TIF.")

with open(lista_archivos_txt, "w") as f:
    for tif in archivos_tif:
        f.write(f"{tif}\n")

# 2. Construir el Mosaico Virtual (VRT)
comando_vrt = [
    "gdalbuildvrt",
    "-vrtnodata", valor_nodata,
    "-input_file_list", lista_archivos_txt,
    archivo_vrt
]

print("Construyendo Mosaico Virtual (VRT)...")
subprocess.run(comando_vrt, check=True)

# 3. Traducir y recortar a formato .IMG (HFA)
comando_translate = [
    "gdal_translate",
    "--config", "GDAL_CACHEMAX", "2048",
    "-of", "HFA",
    "-a_srs", epsg,
    "-projwin", *projwin,
    "-tr", *resolucion.split(),
    "-a_nodata", valor_nodata,
    "-co", "USE_SPILL=YES",
    archivo_vrt,
    archivo_salida
]

print(f"Generando mosaico final {archivo_salida} (68 bandas, 10x10m)...")
try:
    subprocess.run(comando_translate, check=True)
    print(f"\n--> ÉXITO: Hoja 0341.IMG generada correctamente en {archivo_salida}")
except subprocess.CalledProcessError:
    print("\n[x] ERROR CRÍTICO de GDAL al generar 0341.IMG.")