import xml.etree.ElementTree as ET
import json
import os

# Paths
xml_path = r"l:\Evolutivos\2026\OpenStreetMaps\AG\ejemplos\santander_sm.xml"
json_path = r"l:\Evolutivos\2026\OpenStreetMaps\AG\src\data\inmuebles.json"

def convert_xml_to_geojson():
    print(f"Reading XML from {xml_path}...")
    try:
        tree = ET.parse(xml_path)
        root = tree.getroot()
    except Exception as e:
        print(f"Error reading XML: {e}")
        return

    new_features = []

    # Iterate over promociones
    for promocion in root.findall('promocion'):
        datos = promocion.find('datos_promocion')
        if datos is None:
            continue

        # Geolocation
        try:
            lat = float(datos.find('latitud').text)
            lon = float(datos.find('longitud').text)
        except (AttributeError, ValueError):
            continue # Skip if no valid coordinates

        # Common data
        poblacion = datos.find('localidad').text if datos.find('localidad') is not None else ""
        calle_node = datos.find('direccion_promocion/Calle')
        calle = calle_node.text if calle_node is not None else ""
        
        # Photos
        photos = []
        for foto in datos.findall('foto'):
            if foto.text:
                photos.append({"urlfotogrande": foto.text.strip()})
        
        img_main = photos[0]['urlfotogrande'] if photos else "https://images.unsplash.com/photo-1560448204-e02f11c3d0e2" # Fallback

        # Iterate over inmuebles within the promocion
        for inmueble in promocion.findall('inmueble'):
            try:
                ref = inmueble.find('referencia').text
                title = f"Inmueble {ref}"
                
                tipo_node = inmueble.find('tipo')
                tipo = tipo_node.text if tipo_node is not None else "Piso"

                precio_node = inmueble.find('precio_venta')
                precio = float(precio_node.text) if precio_node is not None and precio_node.text else 0
                
                hab_node = inmueble.find('habitaciones')
                numhab = int(hab_node.text) if hab_node is not None and hab_node.text else 0
                
                banos_node = inmueble.find('banos')
                numbanos = int(banos_node.text) if banos_node is not None and banos_node.text else 0
                
                surf_node = inmueble.find('m2construidos')
                superficie = float(surf_node.text) if surf_node is not None and surf_node.text else 0

                # Formatted price
                price_fmt = "{:,.0f}".format(precio).replace(",", ".")

                feature = {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [lon, lat]
                    },
                    "properties": {
                        "title": f"{tipo} en {poblacion}",
                        "tipologia": tipo,
                        "referencia": ref,
                        "price": price_fmt,
                        "precio": precio,
                        "superficie": superficie,
                        "numhab": numhab,
                        "numbanos": numbanos,
                        "poblacion": poblacion,
                        "calle": calle,
                        "fotos": photos,
                        "img": img_main,
                        "promo01": 0,
                        "venta01": 1
                    }
                }
                new_features.append(feature)

            except Exception as e:
                print(f"Skipping inmueble due to error: {e}")
                continue

    print(f"Found {len(new_features)} new features.")

    # Load existing JSON
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        print(f"Error reading JSON: {e}")
        return

    # Append
    data['features'].extend(new_features)

    # Save
    with open(json_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4, ensure_ascii=False)
    
    print("Done.")

if __name__ == "__main__":
    convert_xml_to_geojson()
