@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
REM ================== CONFIGURA AQUI ==================
set HOST=localhost
set DB=thirty
set USER=Fresh
set PASS=9j\V<2&2-f02Pre5(R=~E<$wg}.N:B
REM Si PHP no está en PATH, pon la ruta completa (por ejemplo XAMPP):
set PHP_EXE=php
REM set PHP_EXE=C:\xampp\php\php.exe
REM ====================================================

set BASE=%~dp0
set TMP=%BASE%_tmp_locations
set MUN_SRC=%TMP%\municipios.csv
set ES_ZIP=%TMP%\ES.zip
set ES_TXT=%TMP%\ES.txt

set CSV_MUN=%BASE%municipalities_full.csv
set CSV_CP=%BASE%postal_codes_full.csv
set IMPORT_PHP=%BASE%import_locations.php

echo.
echo === Comprobaciones previas ===
where "%PHP_EXE%" >nul 2>&1 || (echo [ERROR] No encuentro PHP: %PHP_EXE% && echo Edita PHP_EXE en este .bat && exit /b 1)
if not exist "%IMPORT_PHP%" (
  echo [ERROR] No encuentro %IMPORT_PHP%
  echo Coloca este .bat en la misma carpeta que import_locations.php
  exit /b 1
)

echo.
echo === 1) Descargando datasets oficiales (PowerShell) ===
mkdir "%TMP%" >nul 2>&1

REM Municipios INE/CodeForSpain
powershell -NoProfile -Command "try { Invoke-WebRequest -UseBasicParsing -Uri 'https://raw.githubusercontent.com/codeforspain/ds-organizacion-administrativa/master/data/municipios.csv' -OutFile '%MUN_SRC%'; exit 0 } catch { Write-Host $_.Exception.Message; exit 1 }"
if errorlevel 1 (echo [ERROR] No se pudo descargar municipios.csv && exit /b 1)

REM GeoNames ES.zip (codigos postales)
powershell -NoProfile -Command "try { Invoke-WebRequest -UseBasicParsing -Uri 'https://download.geonames.org/export/zip/ES.zip' -OutFile '%ES_ZIP%'; exit 0 } catch { Write-Host $_.Exception.Message; exit 1 }"
if errorlevel 1 (echo [ERROR] No se pudo descargar ES.zip && exit /b 1)

echo.
echo === 2) Generando municipalities_full.csv (code,name,province_code) ===
powershell -NoProfile -Command ^
  "$csv = Import-Csv -Path '%MUN_SRC%';" ^
  "$out = @(); $seen = @{};" ^
  "foreach($r in $csv) {" ^
  "  $code = [string]$r.municipio_id;" ^
  "  $prov = ([string]$r.provincia_id).PadLeft(2,'0');" ^
  "  $name = [string]$r.nombre;" ^
  "  if([string]::IsNullOrWhiteSpace($code) -or [string]::IsNullOrWhiteSpace($name) -or [string]::IsNullOrWhiteSpace($prov)) { continue }" ^
  "  if(-not $seen.ContainsKey($code)) { $out += [PSCustomObject]@{ code=$code; name=$name; province_code=$prov }; $seen[$code]=$true }" ^
  "}" ^
  "$out | Export-Csv -Path '%CSV_MUN%' -NoTypeInformation -Encoding UTF8"
if errorlevel 1 (echo [ERROR] Fallo creando %CSV_MUN% && exit /b 1)
if not exist "%CSV_MUN%" (echo [ERROR] No existe %CSV_MUN% && exit /b 1)

echo.
echo === 3) Generando postal_codes_full.csv (postal_code,municipality_name) ===
powershell -NoProfile -Command ^
  "Add-Type -A 'System.IO.Compression.FileSystem';" ^
  "[IO.Compression.ZipFile]::ExtractToDirectory('%ES_ZIP%','%TMP%');" ^
  "$rows = Get-Content -Path '%ES_TXT%';" ^
  "$seen = @{}; $out = @();" ^
  "foreach($line in $rows) {" ^
  "  $parts = $line -split \"`t\"; if($parts.Count -lt 3) { continue }" ^
  "  $cp = $parts[1].Trim(); $mun = $parts[2].Trim();" ^
  "  if([string]::IsNullOrWhiteSpace($cp) -or [string]::IsNullOrWhiteSpace($mun)) { continue }" ^
  "  $key = \"$cp|$mun\"; if(-not $seen.ContainsKey($key)) { $out += [PSCustomObject]@{ postal_code=$cp; municipality_name=$mun }; $seen[$key]=$true }" ^
  "}" ^
  "$out | Export-Csv -Path '%CSV_CP%' -NoTypeInformation -Encoding UTF8"
if errorlevel 1 (echo [ERROR] Fallo creando %CSV_CP% && exit /b 1)
if not exist "%CSV_CP%" (echo [ERROR] No existe %CSV_CP% && exit /b 1)

echo.
echo === 4) Importando en MySQL (provincias + municipios + C.P.) ===
"%PHP_EXE%" "%IMPORT_PHP%" --host=%HOST% --db=%DB% --user=%USER% --pass="%PASS%" --seed-provinces --municipalities="%CSV_MUN%" --postalcodes="%CSV_CP%"
if errorlevel 1 (echo [ERROR] Fallo en import_locations.php && exit /b 1)

echo.
echo === LIMPIEZA TEMPORAL ===
rmdir /s /q "%TMP%" >nul 2>&1

echo.
echo ==== TODO LISTO ====
echo Municipios CSV: "%CSV_MUN%"
echo C.P. CSV     : "%CSV_CP%"
exit /b 0
