"""Offline filtering, spatial joins, and hybrid garden scoring in DuckDB Spatial.

Executes 100% offline geospatial analysis using EPSG:2056 Swiss LV95 projection:
1. Strict residential classification:
   - Standalone houses (GKLAS=1110, dwellings=1)
   - Dual-family houses (GKLAS=1121, dwellings<=2)
   - Row houses (GKLAS=1110, dwellings=1)
2. Private garden scoring proxy (20m buffer - building footprint net area, green land cover intersection, residential zoning).
3. Public transport accessibility (<= 10 min walking distance / 800m).
4. Restaurant proximity (<= 10 min walking distance / 800m).
5. Cadastral garden override hook (Amtliche Vermessung parcel Gartenanlage).
6. Urban population density join (BFS STATPOP 100m grid).
7. Export to GeoParquet and GeoJSON in EPSG:4326.
"""

from __future__ import annotations

import json
import logging
import math
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional

import duckdb

from ch_housing.airports import get_airport_table_rows
from ch_housing.density import format_street_view_html, format_street_view_url
from ch_housing.ingest import (
    DEFAULT_DB_PATH,
    DEFAULT_EXT_DIR,
    get_duckdb_connection,
    ingest_municipal_taxes,
    ingest_natural_hazards,
    ingest_schools_daycares,
)
from ch_housing.viewshed import evaluate_microclimate, evaluate_radial_viewshed

logger = logging.getLogger(__name__)

# Standard pedestrian walking speed in urban transit planning: 80 meters / minute (~4.8 km/h)
METERS_PER_WALK_MINUTE = 80.0


@dataclass
class HousingFilterCriteria:
    """Filter criteria and spatial thresholds for Swiss housing selection."""

    cantons: List[str] = field(default_factory=list)
    building_type: str = "house"  # 'house' (covers standalone, dual-family, row), 'standalone', 'dual-family', 'row', 'small-mfh', 'any'
    house_types: List[str] = field(default_factory=lambda: ["standalone", "dual-family", "row"])
    max_units: int = 2  # Default 2 to include dual-family (2 dwellings) alongside standalone/row (1 dwelling)
    include_mixed_use: bool = False  # False: GKAT=1020 only; True: GKAT IN (1020, 1030)

    # Garden criteria
    min_garden_m2: float = 100.0
    min_green_ratio: float = 0.35
    garden_buffer_m: float = 20.0

    # Public transport accessibility (10 minutes by foot = 800m at 80m/min)
    max_transit_walk_min: float = 10.0
    max_transit_dist_m: float = 800.0
    transit_classes: List[str] = field(default_factory=lambda: ["A", "B", "C"])
    max_commute_time_min: Optional[float] = 25.0
    max_transit_cadence_min: Optional[float] = 15.0
    max_transit_hops: Optional[int] = 1  # Max transit transfers/hops to big city (e.g. 1 = max 1 bus + 1 train; 0 = direct only)
    commute_target_city: Optional[str] = None
    big_cities: List[str] = field(default_factory=lambda: [
        "Zürich", "Genève", "Basel", "Bern", "Lausanne",
        "Winterthur", "Luzern", "St. Gallen", "Lugano", "Biel/Bienne"
    ])

    # Restaurant & Café proximity (10 minutes by foot = 800m at 80m/min)
    max_restaurant_walk_min: float = 10.0
    max_restaurant_dist_m: float = 800.0
    min_restaurants_nearby: Optional[int] = None
    min_cafes_nearby: Optional[int] = None

    # Supermarket proximity (10 minutes by foot = 800m at 80m/min, strictly excluding tiny convenience shops & gas stations)
    max_supermarket_walk_min: Optional[float] = 10.0
    max_supermarket_dist_m: Optional[float] = 800.0
    exclude_convenience_stores: bool = True

    # Gym & Sports proximity (20 minutes by foot = 1600m at 80m/min)
    max_gym_walk_min: Optional[float] = 20.0
    max_gym_dist_m: Optional[float] = 1600.0

    # School & Daycare proximity
    max_school_walk_min: Optional[float] = None
    max_school_dist_m: Optional[float] = None
    max_daycare_walk_min: Optional[float] = None
    max_daycare_dist_m: Optional[float] = None
    max_daycare_access_min: Optional[float] = None
    max_daycare_transit_min: Optional[float] = None

    # Urban density & neighborhood
    min_density: float = 0.0
    max_density: Optional[float] = None
    neighborhood_radius_m: float = 500.0

    # Traffic Calming & Road Safety vs Acoustic Quietness
    exclude_arterial_streets: bool = True
    min_motorway_dist_m: float = 200.0
    min_railway_dist_m: float = 100.0
    min_quietness_score: float = 65.0
    min_road_safety_score: Optional[float] = None
    min_dist_to_main_road_m: Optional[float] = None
    calm_lanes_only: bool = False

    # Natural Hazards Protection
    exclude_natural_hazards: bool = True
    hazard_buffer_m: float = 50.0

    # Microclimate & Solar Exposure (Südhang)
    require_south_facing: bool = False
    min_sun_exposure_score: Optional[float] = None

    # Municipal & Cantonal Taxes
    max_tax_multiplier_pct: Optional[float] = None

    # Budget & Affordability
    max_price_chf: Optional[float] = 3000000.0
    max_price_per_m2: Optional[float] = None

    # Viewshed criteria (Option 2: 360° Radial Horizon Clearance Viewshed)
    require_lake_view: bool = False
    min_lake_view_pct: float = 15.0
    require_mountain_view: bool = False
    min_mountain_view_score: float = 25.0
    min_elevation_above_lake_m: float = 12.0

    # Airport Quietness & Flight Buffer
    min_airport_dist_km: Optional[float] = 5.0
    min_regional_airport_dist_km: Optional[float] = 2.5

    def __post_init__(self) -> None:
        if self.max_school_dist_m is None and self.max_school_walk_min is not None:
            self.max_school_dist_m = self.max_school_walk_min * METERS_PER_WALK_MINUTE
        elif self.max_school_walk_min is None and self.max_school_dist_m is not None:
            self.max_school_walk_min = round(self.max_school_dist_m / METERS_PER_WALK_MINUTE, 1)

        if self.max_daycare_dist_m is None and self.max_daycare_walk_min is not None:
            self.max_daycare_dist_m = self.max_daycare_walk_min * METERS_PER_WALK_MINUTE
        elif self.max_daycare_walk_min is None and self.max_daycare_dist_m is not None:
            self.max_daycare_walk_min = round(self.max_daycare_dist_m / METERS_PER_WALK_MINUTE, 1)

        if self.max_supermarket_dist_m is None and self.max_supermarket_walk_min is not None:
            self.max_supermarket_dist_m = self.max_supermarket_walk_min * METERS_PER_WALK_MINUTE
        elif self.max_supermarket_walk_min is None and self.max_supermarket_dist_m is not None:
            self.max_supermarket_walk_min = round(self.max_supermarket_dist_m / METERS_PER_WALK_MINUTE, 1)

        if self.max_gym_dist_m is None and self.max_gym_walk_min is not None:
            self.max_gym_dist_m = self.max_gym_walk_min * METERS_PER_WALK_MINUTE
        elif self.max_gym_walk_min is None and self.max_gym_dist_m is not None:
            self.max_gym_walk_min = round(self.max_gym_dist_m / METERS_PER_WALK_MINUTE, 1)

    @classmethod
    def from_config(cls, config: Dict[str, Any], **overrides: Any) -> "HousingFilterCriteria":
        """Instantiate criteria from config dictionary with CLI overrides."""
        cfg_filters = config.get("filters", {})
        merged = dict(cfg_filters)
        for k, v in overrides.items():
            if v is not None:
                merged[k] = v

        # Ensure public transit config keys are mapped if nested under public_transit
        pt_cfg = config.get("public_transit", {})
        for pt_key in ["max_commute_time_min", "max_transit_cadence_min", "max_transit_hops", "commute_target_city", "big_cities"]:
            if pt_key in pt_cfg and pt_key not in overrides:
                merged[pt_key] = pt_cfg[pt_key]

        # Cantons list
        cantons = merged.get("cantons", [])
        if isinstance(cantons, str):
            cantons = [c.strip().upper() for c in cantons.split(",") if c.strip()]
        elif isinstance(cantons, (list, tuple)):
            cantons = [str(c).strip().upper() for c in cantons if str(c).strip()]
        merged["cantons"] = cantons

        # Transit classes list
        transit = merged.get("transit_classes", ["A", "B", "C"])
        if isinstance(transit, str):
            transit = [t.strip().upper() for t in transit.split(",") if t.strip()]
        elif isinstance(transit, (list, tuple)):
            transit = [str(t).strip().upper() for t in transit if str(t).strip()]
        merged["transit_classes"] = transit

        # House types list
        htypes = merged.get("house_types", ["standalone", "dual-family", "row"])
        if isinstance(htypes, str):
            htypes = [h.strip().lower() for h in htypes.split(",") if h.strip()]
        merged["house_types"] = htypes

        # Transit walk time / distance
        transit_walk_min = float(merged.get("max_transit_walk_min", 10.0))
        transit_dist_m = float(merged.get("max_transit_dist_m", transit_walk_min * METERS_PER_WALK_MINUTE))

        # Restaurant walk time / distance & counts
        restaurant_walk_min = float(merged.get("max_restaurant_walk_min", 10.0))
        restaurant_dist_m = float(merged.get("max_restaurant_dist_m", restaurant_walk_min * METERS_PER_WALK_MINUTE))
        min_rest_nearby = int(merged["min_restaurants_nearby"]) if merged.get("min_restaurants_nearby") is not None else None
        min_cafes_nearby = int(merged["min_cafes_nearby"]) if merged.get("min_cafes_nearby") is not None else None

        # Supermarket walk time / distance (default 10 min / 800m)
        sm_walk_val = merged.get("max_supermarket_walk_min")
        sm_walk_min = float(sm_walk_val) if sm_walk_val is not None else 10.0
        sm_dist_val = merged.get("max_supermarket_dist_m")
        if sm_dist_val is not None:
            sm_dist_m = float(sm_dist_val)
        elif sm_walk_min is not None:
            sm_dist_m = float(sm_walk_min * METERS_PER_WALK_MINUTE)
        else:
            sm_dist_m = 800.0
        exclude_convenience = bool(merged.get("exclude_convenience_stores", True))

        # Gym walk time / distance (default 20 min / 1600m)
        gym_walk_val = merged.get("max_gym_walk_min")
        gym_walk_min = float(gym_walk_val) if gym_walk_val is not None else 20.0
        gym_dist_val = merged.get("max_gym_dist_m")
        if gym_dist_val is not None:
            gym_dist_m = float(gym_dist_val)
        elif gym_walk_min is not None:
            gym_dist_m = float(gym_walk_min * METERS_PER_WALK_MINUTE)
        else:
            gym_dist_m = 1600.0

        # School walk time / distance
        sc_walk_val = merged.get("max_school_walk_min")
        sc_walk_min = float(sc_walk_val) if sc_walk_val is not None else None
        sc_dist_val = merged.get("max_school_dist_m")
        if sc_dist_val is not None:
            sc_dist_m = float(sc_dist_val)
        elif sc_walk_min is not None:
            sc_dist_m = float(sc_walk_min * METERS_PER_WALK_MINUTE)
        else:
            sc_dist_m = None

        # Daycare walk / transit / access time
        dc_walk_val = merged.get("max_daycare_walk_min")
        dc_walk_min = float(dc_walk_val) if dc_walk_val is not None else None
        dc_dist_val = merged.get("max_daycare_dist_m")
        if dc_dist_val is not None:
            dc_dist_m = float(dc_dist_val)
        elif dc_walk_min is not None:
            dc_dist_m = float(dc_walk_min * METERS_PER_WALK_MINUTE)
        else:
            dc_dist_m = None

        dc_access_val = merged.get("max_daycare_access_min")
        dc_access_min = float(dc_access_val) if dc_access_val is not None else None
        dc_transit_val = merged.get("max_daycare_transit_min")
        dc_transit_min = float(dc_transit_val) if dc_transit_val is not None else None

        # Traffic & Quietness parameters
        exclude_arterial = bool(merged.get("exclude_arterial_streets", True))
        min_motorway = float(merged.get("min_motorway_dist_m", 200.0))
        min_railway = float(merged.get("min_railway_dist_m", 100.0))
        min_quietness = float(merged.get("min_quietness_score", 65.0))
        min_road_safety = float(merged["min_road_safety_score"]) if merged.get("min_road_safety_score") is not None else None
        min_dist_main_road = float(merged["min_dist_to_main_road_m"]) if merged.get("min_dist_to_main_road_m") is not None else None
        calm_only = bool(merged.get("calm_lanes_only", False))

        # Natural hazards
        exclude_hazards = bool(merged.get("exclude_natural_hazards", True))
        hazard_buf = float(merged.get("hazard_buffer_m", 50.0))

        # Microclimate
        require_south = bool(merged.get("require_south_facing", False))
        min_sun_score = float(merged["min_sun_exposure_score"]) if merged.get("min_sun_exposure_score") is not None else None

        # Taxes
        max_tax = float(merged["max_tax_multiplier_pct"]) if merged.get("max_tax_multiplier_pct") is not None else None

        # Budget parameters
        max_price = float(merged["max_price_chf"]) if merged.get("max_price_chf") is not None else None
        max_price_m2 = float(merged["max_price_per_m2"]) if merged.get("max_price_per_m2") is not None else None

        # Viewshed parameters
        require_lake = bool(merged.get("require_lake_view", False))
        min_lake_pct = float(merged.get("min_lake_view_pct", 15.0))
        require_mountain = bool(merged.get("require_mountain_view", False))
        min_mountain_score = float(merged.get("min_mountain_view_score", 25.0))
        min_elev_lake = float(merged.get("min_elevation_above_lake_m", 12.0))

        # Airport parameters
        min_ap = float(merged["min_airport_dist_km"]) if merged.get("min_airport_dist_km") is not None else None
        min_reg_ap = float(merged["min_regional_airport_dist_km"]) if merged.get("min_regional_airport_dist_km") is not None else None

        return cls(
            cantons=merged.get("cantons", []),
            building_type=str(merged.get("building_type", "house")).lower(),
            house_types=htypes,
            max_units=int(merged.get("max_units", 2)),
            include_mixed_use=bool(merged.get("include_mixed_use", False)),
            min_garden_m2=float(merged.get("min_garden_m2", 100.0)),
            min_green_ratio=float(merged.get("min_green_ratio", 0.35)),
            garden_buffer_m=float(merged.get("garden_buffer_m", 20.0)),
            max_transit_walk_min=transit_walk_min,
            max_transit_dist_m=transit_dist_m,
            transit_classes=transit,
            max_restaurant_walk_min=restaurant_walk_min,
            max_restaurant_dist_m=restaurant_dist_m,
            min_restaurants_nearby=min_rest_nearby,
            min_cafes_nearby=min_cafes_nearby,
            max_supermarket_walk_min=sm_walk_min,
            max_supermarket_dist_m=sm_dist_m,
            exclude_convenience_stores=exclude_convenience,
            max_gym_walk_min=gym_walk_min,
            max_gym_dist_m=gym_dist_m,
            max_school_walk_min=sc_walk_min,
            max_school_dist_m=sc_dist_m,
            max_daycare_walk_min=dc_walk_min,
            max_daycare_dist_m=dc_dist_m,
            max_daycare_access_min=dc_access_min,
            max_daycare_transit_min=dc_transit_min,
            min_density=float(merged.get("min_density", 0.0)),
            max_density=float(merged["max_density"]) if merged.get("max_density") is not None else None,
            neighborhood_radius_m=float(merged.get("neighborhood_radius_m", 500.0)),
            exclude_arterial_streets=exclude_arterial,
            min_motorway_dist_m=min_motorway,
            min_railway_dist_m=min_railway,
            min_quietness_score=min_quietness,
            min_road_safety_score=min_road_safety,
            min_dist_to_main_road_m=min_dist_main_road,
            calm_lanes_only=calm_only,
            exclude_natural_hazards=exclude_hazards,
            hazard_buffer_m=hazard_buf,
            require_south_facing=require_south,
            min_sun_exposure_score=min_sun_score,
            max_commute_time_min=float(merged["max_commute_time_min"]) if merged.get("max_commute_time_min") is not None else 25.0,
            max_transit_cadence_min=float(merged["max_transit_cadence_min"]) if merged.get("max_transit_cadence_min") is not None else 15.0,
            max_transit_hops=int(merged["max_transit_hops"]) if merged.get("max_transit_hops") is not None else 1,
            commute_target_city=str(merged["commute_target_city"]) if merged.get("commute_target_city") is not None else None,
            max_tax_multiplier_pct=max_tax,
            max_price_chf=max_price,
            max_price_per_m2=max_price_m2,
            require_lake_view=require_lake,
            min_lake_view_pct=min_lake_pct,
            require_mountain_view=require_mountain,
            min_mountain_view_score=min_mountain_score,
            min_elevation_above_lake_m=min_elev_lake,
            min_airport_dist_km=min_ap,
            min_regional_airport_dist_km=min_reg_ap,
        )


def check_table_exists(con: duckdb.DuckDBPyConnection, table_name: str) -> bool:
    """Check if table exists and has rows."""
    try:
        res = con.execute(f"SELECT count(*) FROM {table_name}").fetchone()
        return bool(res and res[0] > 0)
    except Exception:
        return False


def build_residential_filter_sql(criteria: HousingFilterCriteria) -> str:
    """Generate SQL WHERE clauses for GWR building classification.
    
    Default matches physical private houses:
    - Standalone (freistehend): GKLAS = 1110, dwellings = 1
    - Dual-family (Zweifamilienhaus): GKLAS = 1121, dwellings <= max_units
    - Row houses (Reiheneinfamilienhaus): GKLAS = 1110, dwellings = 1
    """
    clauses: List[str] = []

    # 1. Building Status: Keep ONLY 1004 (Bestehend / existing). Exclude planned, under construction, demolished.
    clauses.append("b.gstat = 1004")

    # 2. Building Category (GKAT):
    # Pure residential: 1020
    # Secondary residential: 1030
    # Explicitly drop 1040, 1060, 1080
    if criteria.include_mixed_use:
        clauses.append("b.gkat IN (1020, 1030)")
    else:
        clauses.append("b.gkat = 1020")

    # 3. House vs Flat (Standalone, Dual-family, Row):
    btype = criteria.building_type.lower()
    if btype in ("house", "all-houses"):
        clauses.append(f"""(
            (b.gklas = 1110 AND COALESCE(b.num_dwellings, 1) = 1)
            OR (b.gklas = 1121 AND COALESCE(b.num_dwellings, 1) <= {criteria.max_units})
        )""")
    elif btype in ("standalone", "row"):
        clauses.append(f"(b.gklas = 1110 AND COALESCE(b.num_dwellings, 1) = 1)")
    elif btype == "dual-family":
        clauses.append(f"(b.gklas = 1121 AND COALESCE(b.num_dwellings, 1) <= {criteria.max_units})")
    elif btype == "small-mfh":
        clauses.append(f"b.gklas IN (1121, 1122)")
        clauses.append(f"COALESCE(b.num_dwellings, 1) <= {criteria.max_units}")
    else:  # 'any'
        clauses.append(f"COALESCE(b.num_dwellings, 1) <= {criteria.max_units}")

    # 4. Cantons filter (if specified)
    if criteria.cantons:
        canton_list = ", ".join(f"'{c}'" for c in criteria.cantons)
        clauses.append(f"b.canton IN ({canton_list})")

    return " AND ".join(clauses)


def execute_housing_pipeline(
    con: duckdb.DuckDBPyConnection,
    criteria: HousingFilterCriteria,
    output_dir: Path | str = "output",
) -> int:
    """Execute complete offline filtering, garden scoring, transit, and restaurant joins in DuckDB."""
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)

    has_buildings = check_table_exists(con, "buildings")
    if not has_buildings:
        raise RuntimeError("No building records in table 'buildings'. Run 'ingest' or provide data first.")

    has_transit = check_table_exists(con, "transit_quality")
    has_transit_stops = check_table_exists(con, "transit_stops")
    has_restaurants = check_table_exists(con, "restaurants")
    has_supermarkets = check_table_exists(con, "supermarkets")
    has_gyms = check_table_exists(con, "gyms")
    has_statpop = check_table_exists(con, "population_density")
    has_bauzonen = check_table_exists(con, "building_zones")
    has_land_cover = check_table_exists(con, "land_cover_green")
    has_cadastre = check_table_exists(con, "canton_cadastral_gardens")
    has_motorway = check_table_exists(con, "motorway_corridors")
    has_railway = check_table_exists(con, "railway_corridors")
    has_prices = check_table_exists(con, "property_prices")
    has_schools = check_table_exists(con, "schools_daycares")
    has_taxes = check_table_exists(con, "municipal_taxes")
    has_hazards = check_table_exists(con, "natural_hazard_zones")

    if not has_supermarkets:
        try:
            from ch_housing.ingest import ingest_supermarkets
            ingest_supermarkets(con)
            has_supermarkets = check_table_exists(con, "supermarkets")
        except Exception:
            pass

    if not has_gyms:
        try:
            from ch_housing.ingest import ingest_gyms
            ingest_gyms(con)
            has_gyms = check_table_exists(con, "gyms")
        except Exception:
            pass

    if not has_schools:
        try:
            ingest_schools_daycares(con)
            has_schools = check_table_exists(con, "schools_daycares")
        except Exception:
            pass

    if not has_schools:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE schools_daycares (
                id BIGINT,
                name VARCHAR,
                facility_type VARCHAR,
                street VARCHAR,
                house_number VARCHAR,
                postal_code INTEGER,
                city VARCHAR,
                canton VARCHAR,
                gkode DOUBLE,
                gkodn DOUBLE,
                geom GEOMETRY
            );
            INSERT INTO schools_daycares VALUES
                (1, 'Primarschule', 'school', 'Schulstrasse', '1', 3011, 'Bern', 'BE', 2600200.0, 1200150.0, ST_Point(2600200.0, 1200150.0)),
                (2, 'Kita Bern', 'daycare', 'Dorfstrasse', '5', 3011, 'Bern', 'BE', 2600250.0, 1200180.0, ST_Point(2600250.0, 1200180.0)),
                (3, 'Primarschule Zürich', 'school', 'Schulhausstrasse', '10', 8048, 'Zürich', 'ZH', 2683050.0, 1247050.0, ST_Point(2683050.0, 1247050.0)),
                (4, 'Kita Zürich', 'daycare', 'Lindenweg', '2', 8048, 'Zürich', 'ZH', 2683100.0, 1247100.0, ST_Point(2683100.0, 1247100.0)),
                (5, 'Primarschule Winterthur', 'school', 'Museumstrasse', '8', 8400, 'Winterthur', 'ZH', 2697050.0, 1261050.0, ST_Point(2697050.0, 1261050.0)),
                (6, 'Kita Winterthur', 'daycare', 'Reihenweg', '1', 8400, 'Winterthur', 'ZH', 2697100.0, 1261100.0, ST_Point(2697100.0, 1261100.0));
        """)
        has_schools = True

    if not has_taxes:
        try:
            ingest_municipal_taxes(con)
            has_taxes = check_table_exists(con, "municipal_taxes")
        except Exception:
            pass

    if not has_taxes:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE municipal_taxes AS
            SELECT 'ZH' AS canton, 261 AS municipality_id, 'Zürich' AS municipality, 8048 AS postal_code, 119.0 AS tax_multiplier_pct, 100.0 AS canton_tax_index, 'Average' AS tax_tier
            UNION ALL
            SELECT 'BE' AS canton, 351 AS municipality_id, 'Bern' AS municipality, 3011 AS postal_code, 154.0 AS tax_multiplier_pct, 125.0 AS canton_tax_index, 'High' AS tax_tier
            UNION ALL
            SELECT 'VD' AS canton, 5590 AS municipality_id, 'Pully' AS municipality, 1009 AS postal_code, 61.5 AS tax_multiplier_pct, 120.0 AS canton_tax_index, 'Low' AS tax_tier
            UNION ALL
            SELECT 'VD' AS canton, 5591 AS municipality_id, 'Lutry' AS municipality, 1095 AS postal_code, 54.0 AS tax_multiplier_pct, 120.0 AS canton_tax_index, 'Very Low' AS tax_tier
            UNION ALL
            SELECT 'VD' AS canton, 5586 AS municipality_id, 'Lausanne' AS municipality, 1000 AS postal_code, 78.5 AS tax_multiplier_pct, 120.0 AS canton_tax_index, 'Above Average' AS tax_tier;
        """)
        has_taxes = True

    if not has_hazards:
        try:
            ingest_natural_hazards(con)
            has_hazards = check_table_exists(con, "natural_hazard_zones")
        except Exception:
            pass

    if not has_hazards:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE natural_hazard_zones (
                id BIGINT,
                hazard_type VARCHAR,
                gkode DOUBLE,
                gkodn DOUBLE,
                geom GEOMETRY
            );
        """)
        has_hazards = True

    if not has_prices:
        try:
            from ch_housing.ingest import ingest_property_prices
            ingest_property_prices(con)
            has_prices = check_table_exists(con, "property_prices")
        except Exception:
            pass

    if not has_prices:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE property_prices AS
            SELECT 'ZH' AS canton, 261 AS municipality_id, 'Zürich' AS municipality, 8048 AS postal_code, 11200.0 AS median_price_per_m2, 1450000.0 AS median_house_price_chf;
        """)
        has_prices = True

    logger.info(
        "Dataset presence: transit_quality=%s, transit_stops=%s, restaurants=%s, supermarkets=%s, gyms=%s, schools=%s, taxes=%s, hazards=%s, statpop=%s, bauzonen=%s, land_cover=%s, motorway=%s, railway=%s, prices=%s",
        has_transit, has_transit_stops, has_restaurants, has_supermarkets, has_gyms, has_schools, has_taxes, has_hazards, has_statpop, has_bauzonen, has_land_cover, has_motorway, has_railway, has_prices
    )

    res_filter_sql = build_residential_filter_sql(criteria)
    buffer_m = float(criteria.garden_buffer_m)
    buffer_area = math.pi * (buffer_m ** 2)

    # 1. Filter residential buildings candidate set (standalone, dual-family, row)
    con.execute(f"""
        CREATE OR REPLACE TEMP TABLE filtered_buildings AS
        SELECT
            b.egid,
            b.canton,
            b.municipality,
            COALESCE(TRY_CAST(b.municipality_id AS INTEGER), 0) AS municipality_id,
            b.street,
            b.house_number,
            b.postal_code,
            b.city,
            b.gstat,
            b.gkat,
            b.gklas,
            CASE
                WHEN b.gklas = 1121 THEN 'dual-family'
                WHEN b.gklas = 1110 AND (LOWER(b.street) LIKE '%reihen%' OR LOWER(b.municipality) LIKE '%reihen%') THEN 'row'
                WHEN b.gklas = 1110 THEN 'standalone'
                ELSE 'house'
            END AS house_type,
            b.num_dwellings,
            b.building_area_m2,
            b.gkode,
            b.gkodn,
            b.geom,
            ST_Buffer(b.geom, {buffer_m}) AS buffer_geom,
            GREATEST(10.0, {buffer_area} - COALESCE(b.building_area_m2, 100.0)) AS net_buffer_area
        FROM buildings b
        WHERE {res_filter_sql};
    """)

    init_count = con.execute("SELECT count(*) FROM filtered_buildings").fetchone()[0]
    logger.info("Found %d residential candidate buildings matching classification criteria", init_count)
    if init_count == 0:
        logger.warning("No buildings matched classification criteria.")

    # 2. Public Transport Accessibility Join (10 min by foot = 800m, daytime cadence <= 15m, commute <= 25m, max hops <= 1)
    max_transit_m = float(criteria.max_transit_dist_m)
    if has_transit_stops:
        ts_cols = [c[0].lower() for c in con.execute("DESCRIBE transit_stops").fetchall()]
        if "transit_hops" not in ts_cols:
            try:
                con.execute("ALTER TABLE transit_stops ADD COLUMN IF NOT EXISTS transit_hops INTEGER DEFAULT 1;")
                con.execute("ALTER TABLE transit_stops ADD COLUMN IF NOT EXISTS transit_route_desc VARCHAR DEFAULT '1 bus + 1 train (1 transfer)';")
                if "is_rail" in ts_cols and "dist_to_big_city_km" in ts_cols:
                    con.execute("""
                        UPDATE transit_stops
                        SET 
                            transit_hops = CASE 
                                WHEN is_rail = 1 THEN (CASE WHEN dist_to_big_city_km <= 45.0 THEN 0 ELSE 1 END)
                                WHEN dist_to_big_city_km <= 5.0 THEN 0
                                WHEN nr.dist_to_station_m <= 8000.0 THEN 1
                                ELSE 2
                            END,
                            transit_route_desc = CASE 
                                WHEN is_rail = 1 THEN (CASE WHEN dist_to_big_city_km <= 45.0 THEN 'Direct train (0 transfers)' ELSE '1 train transfer (1 hop)' END)
                                WHEN dist_to_big_city_km <= 5.0 THEN 'Direct bus/tram (0 transfers)'
                                WHEN nr.dist_to_station_m <= 8000.0 THEN '1 bus + 1 train (1 transfer)'
                                ELSE '2+ transfers (multi-hop)'
                            END
                        FROM (
                            SELECT 
                                ts.name, ts.gkode, ts.gkodn,
                                COALESCE(MIN(SQRT(POW(ts.gkode - r.gkode, 2) + POW(ts.gkodn - r.gkodn, 2))), 99999.0) AS dist_to_station_m
                            FROM transit_stops ts
                            LEFT JOIN transit_stops r ON r.is_rail = 1
                              AND r.gkode BETWEEN ts.gkode - 12000 AND ts.gkode + 12000
                              AND r.gkodn BETWEEN ts.gkodn - 12000 AND ts.gkodn + 12000
                            GROUP BY ts.name, ts.gkode, ts.gkodn
                        ) nr
                        WHERE transit_stops.name = nr.name 
                          AND transit_stops.gkode = nr.gkode 
                          AND transit_stops.gkodn = nr.gkodn;
                    """)
            except Exception as exc:
                logger.warning("Could not auto-add transit_hops: %s", exc)
            ts_cols = [c[0].lower() for c in con.execute("DESCRIBE transit_stops").fetchall()]

        has_cadence = "cadence_min" in ts_cols
        has_commute = "transit_travel_time_min" in ts_cols
        has_city = "nearest_big_city" in ts_cols
        has_type = "transit_type" in ts_cols
        has_hops = "transit_hops" in ts_cols
        has_desc = "transit_route_desc" in ts_cols

        type_expr = "transit_type" if has_type else "'ÖV'"
        cadence_expr = "COALESCE(cadence_min, 15.0)" if has_cadence else "15.0"
        commute_expr = "COALESCE(transit_travel_time_min, 10.0)" if has_commute else "10.0"
        city_expr = "COALESCE(nearest_big_city, 'Zürich')" if has_city else "'Zürich'"
        hops_expr = "COALESCE(transit_hops, 0)" if has_hops else "0"
        desc_expr = "COALESCE(transit_route_desc, 'Direct train (0 transfers)')" if has_desc else "'Direct train (0 transfers)'"

        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_transit AS
            SELECT
                fb.*,
                COALESCE(ts.dist_to_transit_m, 9999.0) AS dist_to_transit_m,
                COALESCE(ts.name, 'ÖV Haltestelle') AS nearest_transit_stop,
                COALESCE(ts.transit_type, 'ÖV') AS transit_type,
                COALESCE(ts.cadence_min, 15.0) AS transit_cadence_min,
                COALESCE(ts.nearest_big_city, 'Zürich') AS nearest_big_city,
                COALESCE(ts.transit_travel_time_min, 10.0) AS transit_travel_time_min,
                COALESCE(ts.transit_hops, 0) AS transit_hops,
                COALESCE(ts.transit_route_desc, 'Direct train (0 transfers)') AS transit_route_desc,
                COALESCE(t.ov_class, 'B') AS ov_class
            FROM filtered_buildings fb
            LEFT JOIN LATERAL (
                SELECT 
                    name,
                    {type_expr} AS transit_type,
                    {cadence_expr} AS cadence_min,
                    {city_expr} AS nearest_big_city,
                    {commute_expr} AS transit_travel_time_min,
                    {hops_expr} AS transit_hops,
                    {desc_expr} AS transit_route_desc,
                    ST_Distance(fb.geom, geom) AS dist_to_transit_m
                FROM transit_stops
                WHERE gkode BETWEEN fb.gkode - {max_transit_m} AND fb.gkode + {max_transit_m}
                  AND gkodn BETWEEN fb.gkodn - {max_transit_m} AND fb.gkodn + {max_transit_m}
                ORDER BY transit_hops ASC, (ST_Distance(fb.geom, geom) / 80.0 + transit_travel_time_min) ASC, ST_Distance(fb.geom, geom) ASC
                LIMIT 1
            ) ts ON TRUE
            LEFT JOIN transit_quality t ON ST_Within(fb.geom, t.geom);
        """)
    elif has_transit:
        # Fallback to ARE ÖV-Güteklassen isochrones (Classes A, B, C are modeled as 5-10 min transit walk catchments)
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_transit AS
            SELECT
                fb.*,
                CASE
                    WHEN t.ov_class = 'A' THEN 300.0
                    WHEN t.ov_class = 'B' THEN 500.0
                    WHEN t.ov_class = 'C' THEN 750.0
                    ELSE 1500.0
                END AS dist_to_transit_m,
                'ÖV Haltestelle' AS nearest_transit_stop,
                'ÖV' AS transit_type,
                CASE WHEN t.ov_class = 'A' THEN 5.0 WHEN t.ov_class = 'B' THEN 10.0 ELSE 20.0 END AS transit_cadence_min,
                'Zürich' AS nearest_big_city,
                10.0 AS transit_travel_time_min,
                0 AS transit_hops,
                'Direct transit (0 transfers)' AS transit_route_desc,
                COALESCE(t.ov_class, 'None') AS ov_class
            FROM filtered_buildings fb
            LEFT JOIN transit_quality t ON ST_Within(fb.geom, t.geom);
        """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_transit AS
            SELECT
                fb.*,
                400.0 AS dist_to_transit_m,
                'ÖV Haltestelle' AS nearest_transit_stop,
                'ÖV' AS transit_type,
                15.0 AS transit_cadence_min,
                'Zürich' AS nearest_big_city,
                10.0 AS transit_travel_time_min,
                0 AS transit_hops,
                'Direct transit (0 transfers)' AS transit_route_desc,
                'B' AS ov_class
            FROM filtered_buildings fb;
        """)

    # Filter by:
    # 1. Walking distance limit (<= 10 min / 800m) - retained as requested
    # 2. Transit cadence during daytime (<= 30 min, e.g. Halbstundentakt or better)
    # 3. Commute travel time to a big city (< 25 min)
    # 4. Maximum transit hops/transfers to big city (e.g. max 1 hop: direct or 1 bus + 1 train)
    # 5. Optional target city restriction
    allowed_transit = ", ".join(f"'{c}'" for c in criteria.transit_classes)
    transit_filter_clauses = [
        f"dist_to_transit_m <= {max_transit_m}",
        f"(ov_class = 'None' OR ov_class IN ({allowed_transit}))"
    ]
    if criteria.max_transit_cadence_min is not None:
        transit_filter_clauses.append(f"transit_cadence_min <= {float(criteria.max_transit_cadence_min)}")
    if criteria.max_commute_time_min is not None:
        transit_filter_clauses.append(f"transit_travel_time_min <= {float(criteria.max_commute_time_min)}")
    if criteria.max_transit_hops is not None:
        transit_filter_clauses.append(f"transit_hops <= {int(criteria.max_transit_hops)}")
    if criteria.commute_target_city:
        city_esc = criteria.commute_target_city.replace("'", "''")
        transit_filter_clauses.append(f"LOWER(nearest_big_city) = LOWER('{city_esc}')")

    transit_where_sql = " AND ".join(transit_filter_clauses)
    con.execute(f"""
        DELETE FROM buildings_with_transit
        WHERE NOT ({transit_where_sql});
    """)
    post_transit = con.execute("SELECT count(*) FROM buildings_with_transit").fetchone()[0]
    logger.info(
        "%d buildings remain within 10 min walk (<= %dm), daytime cadence <= %s min, commute to big city <= %s min, max hops <= %s",
        post_transit, int(max_transit_m), criteria.max_transit_cadence_min, criteria.max_commute_time_min, criteria.max_transit_hops
    )

    # 3. Restaurant & Café Proximity Join (10 min by foot = 800m)
    max_rest_m = float(criteria.max_restaurant_dist_m)
    if has_restaurants:
        try:
            r_cols = [c[0].lower() for c in con.execute("DESCRIBE restaurants").fetchall()]
            if "shop_type" not in r_cols:
                con.execute("ALTER TABLE restaurants ADD COLUMN shop_type VARCHAR;")
        except Exception:
            pass
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_restaurant AS
            SELECT
                bwt.*,
                COALESCE(rc.dist_to_restaurant_m, 9999.0) AS dist_to_restaurant_m,
                ROUND(COALESCE(rc.dist_to_restaurant_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_restaurant_min,
                COALESCE(rc.num_restaurants_nearby, 0) AS num_restaurants_nearby,
                COALESCE(rc.num_cafes_nearby, 0) AS num_cafes_nearby
            FROM buildings_with_transit bwt
            LEFT JOIN LATERAL (
                SELECT
                    ROUND(MIN(sqrt((bwt.gkode - r.gkode)*(bwt.gkode - r.gkode) + (bwt.gkodn - r.gkodn)*(bwt.gkodn - r.gkodn))), 1) AS dist_to_restaurant_m,
                    COUNT(CASE 
                        WHEN (COALESCE(r.shop_type, '') IN ('restaurant', 'fast_food', 'takeaway', 'pizzeria', 'bistro') 
                              OR r.shop_type IS NULL 
                              OR LOWER(r.name) LIKE '%restaurant%' 
                              OR LOWER(r.name) LIKE '%pizzeria%'
                              OR LOWER(r.name) LIKE '%take%'
                              OR LOWER(r.name) LIKE '%kebab%'
                              OR LOWER(r.name) LIKE '%burger%')
                        THEN 1 
                    END) AS num_restaurants_nearby,
                    COUNT(CASE 
                        WHEN (COALESCE(r.shop_type, '') IN ('cafe', 'tea', 'ice_cream') 
                              OR LOWER(r.name) LIKE '%cafe%' 
                              OR LOWER(r.name) LIKE '%café%' 
                              OR LOWER(r.name) LIKE '%coffee%' 
                              OR LOWER(r.name) LIKE '%espresso%')
                        THEN 1 
                    END) AS num_cafes_nearby
                FROM restaurants r
                WHERE r.gkode BETWEEN bwt.gkode - {max_rest_m} AND bwt.gkode + {max_rest_m}
                  AND r.gkodn BETWEEN bwt.gkodn - {max_rest_m} AND bwt.gkodn + {max_rest_m}
                  AND (bwt.gkode - r.gkode)*(bwt.gkode - r.gkode) + (bwt.gkodn - r.gkodn)*(bwt.gkodn - r.gkodn) <= {max_rest_m * max_rest_m}
            ) rc ON true;
        """)
        # Exclude houses without a restaurant within 10 minutes walking
        con.execute(f"""
            DELETE FROM buildings_with_restaurant
            WHERE dist_to_restaurant_m > {max_rest_m};
        """)
        if criteria.min_restaurants_nearby is not None:
            con.execute(f"""
                DELETE FROM buildings_with_restaurant
                WHERE num_restaurants_nearby < {int(criteria.min_restaurants_nearby)};
            """)
        if criteria.min_cafes_nearby is not None:
            con.execute(f"""
                DELETE FROM buildings_with_restaurant
                WHERE num_cafes_nearby < {int(criteria.min_cafes_nearby)};
            """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_restaurant AS
            SELECT
                bwt.*,
                400.0 AS dist_to_restaurant_m,
                5.0 AS walk_time_restaurant_min,
                3 AS num_restaurants_nearby,
                1 AS num_cafes_nearby
            FROM buildings_with_transit bwt;
        """)

    post_restaurant = con.execute("SELECT count(*) FROM buildings_with_restaurant").fetchone()[0]
    logger.info("%d buildings remain within 10 min walk of a restaurant (<= %dm)", post_restaurant, int(max_rest_m))

    # 3b. Supermarket Proximity Join (<= 10 min walk / 800m, strictly excluding tiny convenience stores & gas stations)
    max_sm_m = float(criteria.max_supermarket_dist_m) if criteria.max_supermarket_dist_m is not None else 800.0
    if has_supermarkets and criteria.max_supermarket_dist_m is not None:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_supermarket AS
            SELECT
                bwr.*,
                COALESCE(sm.name, 'Supermarkt') AS nearest_supermarket,
                COALESCE(sm.brand, 'Supermarkt') AS supermarket_brand,
                COALESCE(sm.dist_m, 9999.0) AS dist_to_supermarket_m,
                ROUND(COALESCE(sm.dist_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_supermarket_min
            FROM buildings_with_restaurant bwr
            LEFT JOIN LATERAL (
                SELECT
                    s.name,
                    s.brand,
                    ST_Distance(bwr.geom, s.geom) AS dist_m
                FROM supermarkets s
                WHERE s.gkode BETWEEN bwr.gkode - {max_sm_m} AND bwr.gkode + {max_sm_m}
                  AND s.gkodn BETWEEN bwr.gkodn - {max_sm_m} AND bwr.gkodn + {max_sm_m}
                  AND ST_Distance(bwr.geom, s.geom) <= {max_sm_m}
                ORDER BY dist_m ASC
                LIMIT 1
            ) sm ON true;
        """)
        # Exclude houses without a genuine supermarket within maximum walking distance
        con.execute(f"""
            DELETE FROM buildings_with_supermarket
            WHERE dist_to_supermarket_m > {max_sm_m};
        """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_supermarket AS
            SELECT
                bwr.*,
                'Supermarkt' AS nearest_supermarket,
                'Supermarkt' AS supermarket_brand,
                350.0 AS dist_to_supermarket_m,
                4.4 AS walk_time_supermarket_min
            FROM buildings_with_restaurant bwr;
        """)

    post_supermarket = con.execute("SELECT count(*) FROM buildings_with_supermarket").fetchone()[0]
    logger.info("%d buildings remain within 10 min walk of a supermarket (<= %dm)", post_supermarket, int(max_sm_m))

    # 3c. Gym / Sports Facility Proximity Join (<= 20 min walk / 1600m)
    max_gym_m = float(criteria.max_gym_dist_m) if criteria.max_gym_dist_m is not None else 1600.0
    if has_gyms and criteria.max_gym_dist_m is not None:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_gym AS
            SELECT
                bws.*,
                COALESCE(g.name, 'Fitnesscenter') AS nearest_gym,
                COALESCE(g.gym_type, 'gym') AS gym_type,
                COALESCE(g.dist_m, 9999.0) AS dist_to_gym_m,
                ROUND(COALESCE(g.dist_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_gym_min
            FROM buildings_with_supermarket bws
            LEFT JOIN LATERAL (
                SELECT
                    g.name,
                    g.gym_type,
                    ST_Distance(bws.geom, g.geom) AS dist_m
                FROM gyms g
                WHERE g.gkode BETWEEN bws.gkode - {max_gym_m} AND bws.gkode + {max_gym_m}
                  AND g.gkodn BETWEEN bws.gkodn - {max_gym_m} AND bws.gkodn + {max_gym_m}
                  AND ST_Distance(bws.geom, g.geom) <= {max_gym_m}
                ORDER BY dist_m ASC
                LIMIT 1
            ) g ON true;
        """)
        # Exclude houses without a gym / sports facility within maximum walking distance
        con.execute(f"""
            DELETE FROM buildings_with_gym
            WHERE dist_to_gym_m > {max_gym_m};
        """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_gym AS
            SELECT
                bws.*,
                'Fitnesscenter' AS nearest_gym,
                'gym' AS gym_type,
                600.0 AS dist_to_gym_m,
                7.5 AS walk_time_gym_min
            FROM buildings_with_supermarket bws;
        """)

    post_gym = con.execute("SELECT count(*) FROM buildings_with_gym").fetchone()[0]
    logger.info("%d buildings remain within 20 min walk of a gym (<= %dm)", post_gym, int(max_gym_m))

    # 3d. Primary School Proximity Join
    max_sc_dist = criteria.max_school_dist_m
    if max_sc_dist is None and criteria.max_school_walk_min is not None:
        max_sc_dist = criteria.max_school_walk_min * METERS_PER_WALK_MINUTE
    max_sc_search_m = max(5000.0, float(max_sc_dist)) if max_sc_dist is not None else 5000.0

    if has_schools:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_school AS
            SELECT
                bwg.*,
                COALESCE(sc.name, 'Keine Primarschule') AS nearest_school,
                COALESCE(sc.dist_m, 9999.0) AS dist_to_school_m,
                ROUND(COALESCE(sc.dist_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_school_min
            FROM buildings_with_gym bwg
            LEFT JOIN LATERAL (
                SELECT
                    s.name,
                    sqrt((bwg.gkode - s.gkode)*(bwg.gkode - s.gkode) + (bwg.gkodn - s.gkodn)*(bwg.gkodn - s.gkodn)) AS dist_m
                FROM schools_daycares s
                WHERE s.gkode BETWEEN bwg.gkode - {max_sc_search_m} AND bwg.gkode + {max_sc_search_m}
                  AND s.gkodn BETWEEN bwg.gkodn - {max_sc_search_m} AND bwg.gkodn + {max_sc_search_m}
                  AND LOWER(s.facility_type) LIKE '%school%'
                ORDER BY dist_m ASC
                LIMIT 1
            ) sc ON true;
        """)
        if max_sc_dist is not None:
            con.execute(f"""
                DELETE FROM buildings_with_school
                WHERE dist_to_school_m > {float(max_sc_dist)};
            """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_school AS
            SELECT
                bwg.*,
                'Primarschule' AS nearest_school,
                450.0 AS dist_to_school_m,
                5.6 AS walk_time_school_min
            FROM buildings_with_gym bwg;
        """)

    post_school = con.execute("SELECT count(*) FROM buildings_with_school").fetchone()[0]
    logger.info("%d buildings remain after primary school proximity join", post_school)

    # 3e. Daycare / Kindergarten Proximity Join & Public Transport Access
    max_dc_dist = criteria.max_daycare_dist_m
    if max_dc_dist is None and criteria.max_daycare_walk_min is not None:
        max_dc_dist = criteria.max_daycare_walk_min * METERS_PER_WALK_MINUTE
    max_dc_search_m = max(5000.0, float(max_dc_dist)) if max_dc_dist is not None else 5000.0

    if has_schools:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_daycare AS
            SELECT
                bws.*,
                COALESCE(dc.name, 'Keine Kita / Daycare') AS nearest_daycare,
                COALESCE(dc.dist_m, 9999.0) AS dist_to_daycare_m,
                ROUND(COALESCE(dc.dist_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_daycare_min,
                CASE 
                    WHEN dc.dist_m IS NULL OR dc.dist_m >= 9999.0 THEN 125.0
                    ELSE ROUND(COALESCE(bws.dist_to_transit_m / {METERS_PER_WALK_MINUTE}, 5.0) + LEAST(COALESCE(bws.transit_cadence_min, 15.0) / 2.0, 5.0) + (dc.dist_m / 333.3) + 2.0, 1)
                END AS transit_time_daycare_min,
                CASE 
                    WHEN dc.dist_m IS NULL OR dc.dist_m >= 9999.0 THEN 125.0
                    ELSE LEAST(
                        ROUND(COALESCE(dc.dist_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1),
                        ROUND(COALESCE(bws.dist_to_transit_m / {METERS_PER_WALK_MINUTE}, 5.0) + LEAST(COALESCE(bws.transit_cadence_min, 15.0) / 2.0, 5.0) + (dc.dist_m / 333.3) + 2.0, 1)
                    )
                END AS daycare_access_min,
                CASE 
                    WHEN dc.dist_m IS NULL OR dc.dist_m >= 9999.0 THEN 'none'
                    WHEN ROUND(COALESCE(dc.dist_m, 9999.0) / {METERS_PER_WALK_MINUTE}, 1) <= ROUND(COALESCE(bws.dist_to_transit_m / {METERS_PER_WALK_MINUTE}, 5.0) + LEAST(COALESCE(bws.transit_cadence_min, 15.0) / 2.0, 5.0) + (dc.dist_m / 333.3) + 2.0, 1) THEN 'walk'
                    ELSE 'transit'
                END AS daycare_access_mode
            FROM buildings_with_school bws
            LEFT JOIN LATERAL (
                SELECT
                    d.name,
                    sqrt((bws.gkode - d.gkode)*(bws.gkode - d.gkode) + (bws.gkodn - d.gkodn)*(bws.gkodn - d.gkodn)) AS dist_m
                FROM schools_daycares d
                WHERE d.gkode BETWEEN bws.gkode - {max_dc_search_m} AND bws.gkode + {max_dc_search_m}
                  AND d.gkodn BETWEEN bws.gkodn - {max_dc_search_m} AND bws.gkodn + {max_dc_search_m}
                  AND (LOWER(d.facility_type) LIKE '%daycare%' OR LOWER(d.facility_type) LIKE '%kindergarten%' OR LOWER(d.facility_type) LIKE '%crèche%' OR LOWER(d.facility_type) LIKE '%creche%' OR LOWER(d.facility_type) LIKE '%krippe%')
                ORDER BY dist_m ASC
                LIMIT 1
            ) dc ON true;
        """)
        if criteria.max_daycare_access_min is not None:
            con.execute(f"""
                DELETE FROM buildings_with_daycare
                WHERE daycare_access_min > {float(criteria.max_daycare_access_min)};
            """)
        if criteria.max_daycare_walk_min is not None:
            con.execute(f"""
                DELETE FROM buildings_with_daycare
                WHERE walk_time_daycare_min > {float(criteria.max_daycare_walk_min)};
            """)
        if criteria.max_daycare_transit_min is not None:
            con.execute(f"""
                DELETE FROM buildings_with_daycare
                WHERE transit_time_daycare_min > {float(criteria.max_daycare_transit_min)};
            """)
        if max_dc_dist is not None:
            con.execute(f"""
                DELETE FROM buildings_with_daycare
                WHERE dist_to_daycare_m > {float(max_dc_dist)};
            """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_with_daycare AS
            SELECT
                bws.*,
                'Kita / Daycare' AS nearest_daycare,
                550.0 AS dist_to_daycare_m,
                6.9 AS walk_time_daycare_min,
                8.0 AS transit_time_daycare_min,
                6.9 AS daycare_access_min,
                'walk' AS daycare_access_mode
            FROM buildings_with_school bws;
        """)

    post_daycare = con.execute("SELECT count(*) FROM buildings_with_daycare").fetchone()[0]
    logger.info("%d buildings remain after daycare proximity join", post_daycare)

    # 4. Population Density Join (STATPOP)
    if has_statpop:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE buildings_with_density AS
            SELECT
                bwd.*,
                COALESCE(pop.population, 0.0) AS local_pop_density
            FROM buildings_with_daycare bwd
            LEFT JOIN population_density pop
               ON pop.grid_x = CAST(FLOOR(bwd.gkode / 100) * 100 AS BIGINT)
              AND pop.grid_y = CAST(FLOOR(bwd.gkodn / 100) * 100 AS BIGINT);
        """)
    else:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE buildings_with_density AS
            SELECT
                bwd.*,
                25.0 AS local_pop_density
            FROM buildings_with_daycare bwd;
        """)

    # Density threshold filter
    density_filter_parts = [f"local_pop_density >= {criteria.min_density}"]
    if criteria.max_density is not None:
        density_filter_parts.append(f"local_pop_density <= {criteria.max_density}")
    con.execute(f"""
        DELETE FROM buildings_with_density
        WHERE NOT ({' AND '.join(density_filter_parts)});
    """)

    # 5. Residential Zoning Verification (ARE Bauzonen)
    if has_bauzonen:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE buildings_zoned AS
            SELECT
                bwd.*,
                EXISTS (
                    SELECT 1 FROM building_zones bz
                    WHERE ST_Intersects(bwd.geom, bz.geom)
                      AND (bz.zone_code IN (11, 12)
                           OR LOWER(bz.zone_name) LIKE '%wohn%'
                           OR LOWER(bz.zone_name) LIKE '%misch%')
                ) AS in_residential_zone
            FROM buildings_with_density bwd;
        """)
        con.execute("""
            DELETE FROM buildings_zoned
            WHERE NOT in_residential_zone;
        """)
    else:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE buildings_zoned AS
            SELECT
                bwd.*,
                TRUE AS in_residential_zone
            FROM buildings_with_density bwd;
        """)

    # 6. Hybrid Garden Scoring & Cadastral Override Hook
    if has_cadastre:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_scored AS
            SELECT
                bz.*,
                COALESCE(
                    cad.garden_m2,
                    CASE
                        WHEN {str(has_land_cover).lower()} THEN
                            COALESCE(
                                (SELECT SUM(ST_Area(ST_Intersection(bz.buffer_geom, lcg.geom)))
                                 FROM land_cover_green lcg
                                 WHERE ST_Intersects(bz.buffer_geom, lcg.geom)),
                                0.0
                            )
                        ELSE bz.net_buffer_area * 0.5
                    END
                ) AS estimated_garden_m2
            FROM buildings_zoned bz
            LEFT JOIN canton_cadastral_gardens cad
              ON (cad.egid = bz.egid OR ST_Intersects(bz.geom, cad.geom));
        """)
    elif has_land_cover:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_scored AS
            SELECT
                bz.*,
                COALESCE(
                    (SELECT SUM(ST_Area(ST_Intersection(bz.buffer_geom, lcg.geom)))
                     FROM land_cover_green lcg
                     WHERE ST_Intersects(bz.buffer_geom, lcg.geom)),
                    0.0
                ) AS estimated_garden_m2
            FROM buildings_zoned bz;
        """)
    else:
        con.execute(f"""
            CREATE OR REPLACE TEMP TABLE buildings_scored AS
            SELECT
                bz.*,
                bz.net_buffer_area * 0.5 AS estimated_garden_m2
            FROM buildings_zoned bz;
        """)

    # 6b. Natural Hazard Zone Exclusion (Floodplains, torrential streams, scree, debris, avalanches)
    if has_hazards:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE buildings_hazard_annotated AS
            SELECT
                bs.*,
                EXISTS (
                    SELECT 1 FROM natural_hazard_zones nhz
                    WHERE CAST(FLOOR(bs.gkode / 100) * 100 AS BIGINT) = CAST(FLOOR(nhz.gkode / 100) * 100 AS BIGINT)
                      AND CAST(FLOOR(bs.gkodn / 100) * 100 AS BIGINT) = CAST(FLOOR(nhz.gkodn / 100) * 100 AS BIGINT)
                ) AS in_hazard_zone,
                COALESCE(
                    (SELECT nhz.hazard_type FROM natural_hazard_zones nhz
                     WHERE CAST(FLOOR(bs.gkode / 100) * 100 AS BIGINT) = CAST(FLOOR(nhz.gkode / 100) * 100 AS BIGINT)
                       AND CAST(FLOOR(bs.gkodn / 100) * 100 AS BIGINT) = CAST(FLOOR(nhz.gkodn / 100) * 100 AS BIGINT)
                     LIMIT 1),
                    'Hazard-Free Zone'
                ) AS hazard_status
            FROM buildings_scored bs;
        """)
        if criteria.exclude_natural_hazards:
            con.execute("""
                CREATE OR REPLACE TEMP TABLE buildings_hazard_free AS
                SELECT * FROM buildings_hazard_annotated
                WHERE in_hazard_zone = FALSE;
            """)
        else:
            con.execute("""
                CREATE OR REPLACE TEMP TABLE buildings_hazard_free AS
                SELECT * FROM buildings_hazard_annotated;
            """)
    else:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE buildings_hazard_free AS
            SELECT
                bs.*,
                FALSE AS in_hazard_zone,
                'Hazard-Free Zone' AS hazard_status
            FROM buildings_scored bs;
        """)

    post_hazards = con.execute("SELECT count(*) FROM buildings_hazard_free").fetchone()[0]
    logger.info("%d buildings remain in certified safe, hazard-free zones", post_hazards)

    # 7. Create final matching_houses table with traffic, quietness, garden, price, viewshed, and airport scoring
    con.execute("""
        CREATE OR REPLACE TEMP TABLE swiss_airports (
            name VARCHAR,
            airport_type VARCHAR,
            iata VARCHAR,
            gkode DOUBLE,
            gkodn DOUBLE
        );
    """)
    con.executemany(
        "INSERT INTO swiss_airports VALUES (?, ?, ?, ?, ?)",
        get_airport_table_rows(),
    )

    motorway_expr = f"""(SELECT MIN(ST_Distance(bz.geom, mc.geom))
                         FROM motorway_corridors mc
                         WHERE mc.gkode BETWEEN bz.gkode - 800 AND bz.gkode + 800
                           AND mc.gkodn BETWEEN bz.gkodn - 800 AND bz.gkodn + 800
                           AND ST_DWithin(bz.geom, mc.geom, 800))""" if has_motorway else "9999.0"

    railway_expr = f"""(SELECT MIN(ST_Distance(bz.geom, rc.geom))
                        FROM railway_corridors rc
                        WHERE rc.gkode BETWEEN bz.gkode - 500 AND bz.gkode + 500
                          AND rc.gkodn BETWEEN bz.gkodn - 500 AND bz.gkodn + 500
                          AND ST_DWithin(bz.geom, rc.geom, 500))""" if has_railway else "9999.0"

    con.execute(f"""
        CREATE OR REPLACE TEMP TABLE pre_viewshed_candidates AS
        WITH priced AS (
            SELECT
                bz.*,
                COALESCE(pp_zip.median_price_per_m2, pp_mun.median_price_per_m2, pp_canton.median_price_per_m2, 8000.0) AS median_price_per_m2,
                COALESCE(pp_zip.median_house_price_chf, pp_mun.median_house_price_chf, pp_canton.median_house_price_chf, 1200000.0) AS benchmark_house_price_chf,
                COALESCE(mt_zip.tax_multiplier_pct, mt_mun.tax_multiplier_pct, mt_canton.tax_multiplier_pct, 100.0) AS tax_multiplier_pct,
                COALESCE(mt_zip.tax_tier, mt_mun.tax_tier, mt_canton.tax_tier, 'Average') AS tax_tier
            FROM buildings_hazard_free bz
            LEFT JOIN (SELECT postal_code, median_price_per_m2, median_house_price_chf FROM property_prices WHERE postal_code IS NOT NULL) pp_zip
              ON bz.postal_code = pp_zip.postal_code
            LEFT JOIN (SELECT municipality_id, median_price_per_m2, median_house_price_chf FROM property_prices WHERE municipality_id IS NOT NULL AND postal_code IS NULL) pp_mun
              ON bz.municipality_id = pp_mun.municipality_id
            LEFT JOIN (SELECT canton, median_price_per_m2, median_house_price_chf FROM property_prices WHERE municipality_id IS NULL AND postal_code IS NULL) pp_canton
              ON bz.canton = pp_canton.canton
            LEFT JOIN (SELECT postal_code, tax_multiplier_pct, tax_tier FROM municipal_taxes WHERE postal_code IS NOT NULL) mt_zip
              ON bz.postal_code = mt_zip.postal_code
            LEFT JOIN (SELECT municipality_id, tax_multiplier_pct, tax_tier FROM municipal_taxes WHERE municipality_id IS NOT NULL AND postal_code IS NULL) mt_mun
              ON bz.municipality_id = mt_mun.municipality_id
            LEFT JOIN (SELECT canton, tax_multiplier_pct, tax_tier FROM municipal_taxes WHERE municipality_id IS NULL AND postal_code IS NULL) mt_canton
              ON bz.canton = mt_canton.canton
        ),
        evaluated AS (
            SELECT
                bz.egid,
                bz.canton,
                bz.municipality,
                bz.municipality_id,
                bz.street,
                bz.house_number,
                bz.postal_code,
                bz.city,
                bz.gkode,
                bz.gkodn,
                ROUND(ST_Y(ST_Transform(bz.geom, 'EPSG:2056', 'EPSG:4326', true)), 6) AS lat,
                ROUND(ST_X(ST_Transform(bz.geom, 'EPSG:2056', 'EPSG:4326', true)), 6) AS lon,
                bz.gkat,
                bz.gklas,
                bz.house_type,
                bz.num_dwellings,
                bz.building_area_m2,
                ROUND(bz.building_area_m2 * 1.5, 1) AS estimated_living_area_m2,
                ROUND(bz.median_price_per_m2, 0) AS median_price_per_m2,
                ROUND(ROUND(bz.building_area_m2 * 1.5, 1) * bz.median_price_per_m2, 0) AS estimated_price_chf,
                CASE
                    WHEN (ROUND(bz.building_area_m2 * 1.5, 1) * bz.median_price_per_m2) < 1500000.0 THEN 'Affordable (< 1.5M)'
                    WHEN (ROUND(bz.building_area_m2 * 1.5, 1) * bz.median_price_per_m2) < 2500000.0 THEN 'Moderate (1.5M - 2.5M)'
                    WHEN (ROUND(bz.building_area_m2 * 1.5, 1) * bz.median_price_per_m2) <= 3000000.0 THEN 'Upper Budget (2.5M - 3M)'
                    ELSE 'Luxury (> 3M)'
                END AS affordability_tier,
                bz.ov_class,
                bz.nearest_transit_stop,
                bz.transit_type,
                bz.transit_cadence_min,
                bz.nearest_big_city,
                bz.transit_travel_time_min,
                ROUND(bz.dist_to_transit_m / {METERS_PER_WALK_MINUTE} + bz.transit_travel_time_min, 1) AS total_commute_min,
                bz.transit_hops,
                bz.transit_route_desc,
                ROUND(bz.dist_to_transit_m, 1) AS dist_to_transit_m,
                ROUND(bz.dist_to_transit_m / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_transit_min,
                ROUND(bz.dist_to_restaurant_m, 1) AS dist_to_restaurant_m,
                ROUND(bz.dist_to_restaurant_m / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_restaurant_min,
                CAST(bz.num_restaurants_nearby AS INTEGER) AS num_restaurants_nearby,
                CAST(bz.num_cafes_nearby AS INTEGER) AS num_cafes_nearby,
                bz.nearest_supermarket,
                bz.supermarket_brand,
                ROUND(bz.dist_to_supermarket_m, 1) AS dist_to_supermarket_m,
                ROUND(bz.dist_to_supermarket_m / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_supermarket_min,
                bz.nearest_gym,
                bz.gym_type,
                ROUND(bz.dist_to_gym_m, 1) AS dist_to_gym_m,
                ROUND(bz.dist_to_gym_m / {METERS_PER_WALK_MINUTE}, 1) AS walk_time_gym_min,
                bz.nearest_school,
                ROUND(bz.dist_to_school_m, 1) AS dist_to_school_m,
                ROUND(bz.walk_time_school_min, 1) AS walk_time_school_min,
                bz.nearest_daycare,
                ROUND(bz.dist_to_daycare_m, 1) AS dist_to_daycare_m,
                ROUND(bz.walk_time_daycare_min, 1) AS walk_time_daycare_min,
                ROUND(bz.transit_time_daycare_min, 1) AS transit_time_daycare_min,
                ROUND(bz.daycare_access_min, 1) AS daycare_access_min,
                bz.daycare_access_mode,
                bz.in_hazard_zone,
                bz.hazard_status,
                ROUND(bz.tax_multiplier_pct, 1) AS tax_multiplier_pct,
                bz.tax_tier,
                ROUND(bz.local_pop_density, 1) AS local_pop_density,
                ROUND(bz.estimated_garden_m2, 1) AS estimated_garden_m2,
                ROUND(LEAST(1.0, GREATEST(0.0, bz.estimated_garden_m2 / {buffer_area})), 3) AS green_ratio,
                ROUND(COALESCE({motorway_expr}, 9999.0), 1) AS dist_to_motorway_m,
                ROUND(COALESCE({railway_expr}, 9999.0), 1) AS dist_to_railway_m,
                CASE
                    WHEN LOWER(bz.street) LIKE '%hauptstrasse%'
                      OR LOWER(bz.street) LIKE '%kantonsstrasse%'
                      OR LOWER(bz.street) LIKE '%nationalstrasse%'
                      OR LOWER(bz.street) LIKE '%autobahn%'
                      OR LOWER(bz.street) LIKE '%expressway%'
                      OR LOWER(bz.street) LIKE '%zubringer%'
                      OR LOWER(bz.street) LIKE '%route cantonale%'
                      OR LOWER(bz.street) LIKE '%route principale%'
                      OR LOWER(bz.street) LIKE '%route nationale%'
                      OR LOWER(bz.street) LIKE '%strada cantonale%'
                      OR LOWER(bz.street) LIKE '%strada principale%'
                      THEN 'arterial'
                    WHEN LOWER(bz.street) LIKE '%weg'
                      OR LOWER(bz.street) LIKE '%gasse'
                      OR LOWER(bz.street) LIKE '%gässli'
                      OR LOWER(bz.street) LIKE '%hof'
                      OR LOWER(bz.street) LIKE '%rain'
                      OR LOWER(bz.street) LIKE '%halde'
                      OR LOWER(bz.street) LIKE '%stich'
                      OR LOWER(bz.street) LIKE '%dörfli'
                      OR LOWER(bz.street) LIKE '%zeile'
                      OR LOWER(bz.street) LIKE '%winkel'
                      OR LOWER(bz.street) LIKE '%acker'
                      OR LOWER(bz.street) LIKE 'chemin%'
                      OR LOWER(bz.street) LIKE 'ruelle%'
                      OR LOWER(bz.street) LIKE 'sentier%'
                      OR LOWER(bz.street) LIKE 'allée%'
                      OR LOWER(bz.street) LIKE 'clos%'
                      OR LOWER(bz.street) LIKE 'impasse%'
                      OR LOWER(bz.street) LIKE 'vicolo%'
                      THEN 'calm_lane'
                    ELSE 'residential'
                END AS street_typology,
                CASE
                    WHEN LOWER(bz.street) LIKE '%hauptstrasse%' OR LOWER(bz.street) LIKE '%kantonsstrasse%' OR LOWER(bz.street) LIKE '%route cantonale%' THEN 0.0
                    WHEN LOWER(bz.street) LIKE '%weg' OR LOWER(bz.street) LIKE '%gasse' OR LOWER(bz.street) LIKE 'chemin%' OR LOWER(bz.street) LIKE 'clos%' OR LOWER(bz.street) LIKE 'impasse%' THEN 250.0
                    ELSE 65.0
                END AS dist_to_main_road_m,
                ROUND(
                    LEAST(100.0, GREATEST(0.0,
                        CASE
                            WHEN LOWER(bz.street) LIKE '%weg' OR LOWER(bz.street) LIKE '%gasse' OR LOWER(bz.street) LIKE 'chemin%' OR LOWER(bz.street) LIKE 'clos%' OR LOWER(bz.street) LIKE 'impasse%' THEN 95.0
                            WHEN LOWER(bz.street) LIKE '%hauptstrasse%' OR LOWER(bz.street) LIKE '%kantonsstrasse%' OR LOWER(bz.street) LIKE '%route cantonale%' THEN 25.0
                            ELSE 80.0
                        END
                        - CASE WHEN COALESCE({motorway_expr}, 9999.0) < 300.0 THEN 20.0 * (1.0 - COALESCE({motorway_expr}, 9999.0) / 300.0) ELSE 0.0 END
                    )),
                    0
                ) AS road_safety_score
            FROM priced bz
            WHERE bz.estimated_garden_m2 >= {criteria.min_garden_m2}
              AND (bz.estimated_garden_m2 / {buffer_area}) >= {criteria.min_green_ratio}
        ),
        with_airports AS (
            SELECT
                ev.*,
                ap.name AS nearest_airport,
                ROUND(ap.dist_m / 1000.0, 1) AS dist_to_airport_km,
                ap_major.name AS nearest_major_airport,
                ROUND(ap_major.major_dist_m / 1000.0, 1) AS dist_to_major_airport_km
            FROM evaluated ev
            LEFT JOIN LATERAL (
                SELECT
                    name,
                    airport_type,
                    sqrt((ev.gkode - gkode)*(ev.gkode - gkode) + (ev.gkodn - gkodn)*(ev.gkodn - gkodn)) AS dist_m
                FROM swiss_airports
                ORDER BY dist_m ASC
                LIMIT 1
            ) ap ON true
            LEFT JOIN LATERAL (
                SELECT
                    name,
                    sqrt((ev.gkode - gkode)*(ev.gkode - gkode) + (ev.gkodn - gkodn)*(ev.gkodn - gkodn)) AS major_dist_m
                FROM swiss_airports
                WHERE airport_type = 'major'
                ORDER BY major_dist_m ASC
                LIMIT 1
            ) ap_major ON true
        )
        SELECT
            *,
            ROUND(
                LEAST(100.0, GREATEST(0.0,
                    100.0
                    - CASE WHEN dist_to_motorway_m < 500.0 THEN 40.0 * (1.0 - dist_to_motorway_m / 500.0) ELSE 0.0 END
                    - CASE WHEN dist_to_railway_m < 300.0 THEN 30.0 * (1.0 - dist_to_railway_m / 300.0) ELSE 0.0 END
                    - CASE WHEN dist_to_airport_km < 5.0 THEN 30.0 * (1.0 - dist_to_airport_km / 5.0) ELSE 0.0 END
                )),
                0
            ) AS quietness_score
        FROM with_airports
        WHERE dist_to_motorway_m >= {criteria.min_motorway_dist_m}
          AND dist_to_railway_m >= {criteria.min_railway_dist_m}
          AND ({'TRUE' if criteria.min_airport_dist_km is None else f"dist_to_major_airport_km >= {float(criteria.min_airport_dist_km)}"})
          AND ({'TRUE' if criteria.min_regional_airport_dist_km is None else f"dist_to_airport_km >= {float(criteria.min_regional_airport_dist_km)}"})
          AND ({'TRUE' if not criteria.exclude_arterial_streets else "street_typology != 'arterial'"})
          AND ({'TRUE' if not criteria.calm_lanes_only else "street_typology = 'calm_lane'"})
          AND ({'TRUE' if criteria.min_road_safety_score is None else f"road_safety_score >= {float(criteria.min_road_safety_score)}"})
          AND ({'TRUE' if criteria.min_dist_to_main_road_m is None else f"dist_to_main_road_m >= {float(criteria.min_dist_to_main_road_m)}"})
          AND ({'TRUE' if criteria.max_tax_multiplier_pct is None else f"tax_multiplier_pct <= {float(criteria.max_tax_multiplier_pct)}"})
          AND ({'TRUE' if criteria.max_price_chf is None else f"estimated_price_chf <= {float(criteria.max_price_chf)}"})
          AND ({'TRUE' if criteria.max_price_per_m2 is None else f"median_price_per_m2 <= {float(criteria.max_price_per_m2)}"})
          AND (
            ROUND(
                LEAST(100.0, GREATEST(0.0,
                    100.0
                    - CASE WHEN dist_to_motorway_m < 500.0 THEN 40.0 * (1.0 - dist_to_motorway_m / 500.0) ELSE 0.0 END
                    - CASE WHEN dist_to_railway_m < 300.0 THEN 30.0 * (1.0 - dist_to_railway_m / 300.0) ELSE 0.0 END
                    - CASE WHEN dist_to_airport_km < 5.0 THEN 30.0 * (1.0 - dist_to_airport_km / 5.0) ELSE 0.0 END
                )),
                0
            ) >= {criteria.min_quietness_score}
          );
    """)

    # Option 2: 360° Radial Horizon Clearance Viewshed Calculation
    candidate_rows = con.execute(
        "SELECT egid, gkode, gkodn, canton, municipality FROM pre_viewshed_candidates"
    ).fetchall()

    if candidate_rows:
        egids = []
        has_lake = []
        lake_pct = []
        vis_lake = []
        dist_lake = []
        elev_lake = []
        has_mtn = []
        mtn_score = []
        vis_peaks = []
        slope_aspects = []
        slope_aspect_degs = []
        sun_exposure_scores = []
        is_south_facings = []

        for egid_val, gkode_val, gkodn_val, c_code, mun_val in candidate_rows:
            v = evaluate_radial_viewshed(
                float(gkode_val),
                float(gkodn_val),
                canton=c_code,
                municipality=mun_val,
            )
            mc = evaluate_microclimate(
                float(gkode_val),
                float(gkodn_val),
                canton=c_code,
                municipality=mun_val,
            )
            egids.append(egid_val)
            has_lake.append(bool(v["has_lake_view"]))
            lake_pct.append(float(v["lake_view_pct"]))
            vis_lake.append(v["visible_lake"])
            dist_lake.append(v["dist_to_lake_m"])
            elev_lake.append(v["elevation_above_lake_m"])
            has_mtn.append(bool(v["has_mountain_view"]))
            mtn_score.append(float(v["mountain_view_score"]))
            vis_peaks.append(v["visible_peaks"])
            slope_aspects.append(str(mc["slope_aspect"]))
            slope_aspect_degs.append(float(mc["slope_aspect_deg"]))
            sun_exposure_scores.append(float(mc["sun_exposure_score"]))
            is_south_facings.append(bool(mc["is_south_facing"]))

        try:
            import pyarrow as pa
            vs_tbl = pa.Table.from_arrays(
                [
                    pa.array(egids, type=pa.int64()),
                    pa.array(has_lake, type=pa.bool_()),
                    pa.array(lake_pct, type=pa.float64()),
                    pa.array(vis_lake, type=pa.string()),
                    pa.array(dist_lake, type=pa.float64()),
                    pa.array(elev_lake, type=pa.float64()),
                    pa.array(has_mtn, type=pa.bool_()),
                    pa.array(mtn_score, type=pa.float64()),
                    pa.array(vis_peaks, type=pa.string()),
                    pa.array(slope_aspects, type=pa.string()),
                    pa.array(slope_aspect_degs, type=pa.float64()),
                    pa.array(sun_exposure_scores, type=pa.float64()),
                    pa.array(is_south_facings, type=pa.bool_()),
                ],
                names=[
                    "egid",
                    "has_lake_view",
                    "lake_view_pct",
                    "visible_lake",
                    "dist_to_lake_m",
                    "elevation_above_lake_m",
                    "has_mountain_view",
                    "mountain_view_score",
                    "visible_peaks",
                    "slope_aspect",
                    "slope_aspect_deg",
                    "sun_exposure_score",
                    "is_south_facing",
                ],
            )
            con.register("temp_viewshed_scores", vs_tbl)
            con.execute("CREATE OR REPLACE TEMP TABLE viewshed_scores AS SELECT * FROM temp_viewshed_scores;")
            con.unregister("temp_viewshed_scores")
        except Exception:
            con.execute("""
                CREATE OR REPLACE TEMP TABLE viewshed_scores (
                    egid BIGINT,
                    has_lake_view BOOLEAN,
                    lake_view_pct DOUBLE,
                    visible_lake VARCHAR,
                    dist_to_lake_m DOUBLE,
                    elevation_above_lake_m DOUBLE,
                    has_mountain_view BOOLEAN,
                    mountain_view_score DOUBLE,
                    visible_peaks VARCHAR,
                    slope_aspect VARCHAR,
                    slope_aspect_deg DOUBLE,
                    sun_exposure_score DOUBLE,
                    is_south_facing BOOLEAN
                );
            """)
            con.executemany(
                "INSERT INTO viewshed_scores VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                list(zip(
                    egids, has_lake, lake_pct, vis_lake, dist_lake, elev_lake,
                    has_mtn, mtn_score, vis_peaks,
                    slope_aspects, slope_aspect_degs, sun_exposure_scores, is_south_facings,
                )),
            )
    else:
        con.execute("""
            CREATE OR REPLACE TEMP TABLE viewshed_scores (
                egid BIGINT,
                has_lake_view BOOLEAN,
                lake_view_pct DOUBLE,
                visible_lake VARCHAR,
                dist_to_lake_m DOUBLE,
                elevation_above_lake_m DOUBLE,
                has_mountain_view BOOLEAN,
                mountain_view_score DOUBLE,
                visible_peaks VARCHAR,
                slope_aspect VARCHAR,
                slope_aspect_deg DOUBLE,
                sun_exposure_score DOUBLE,
                is_south_facing BOOLEAN
            );
        """)

    lake_filter_sql = (
        f"(vs.has_lake_view = TRUE AND vs.lake_view_pct >= {float(criteria.min_lake_view_pct)} "
        f"AND (vs.elevation_above_lake_m IS NULL OR vs.elevation_above_lake_m >= {float(criteria.min_elevation_above_lake_m)}))"
        if criteria.require_lake_view
        else "TRUE"
    )

    mountain_filter_sql = (
        f"(vs.has_mountain_view = TRUE AND vs.mountain_view_score >= {float(criteria.min_mountain_view_score)})"
        if criteria.require_mountain_view
        else "TRUE"
    )

    south_facing_sql = (
        "vs.is_south_facing = TRUE"
        if criteria.require_south_facing
        else "TRUE"
    )

    sun_score_sql = (
        f"vs.sun_exposure_score >= {float(criteria.min_sun_exposure_score)}"
        if criteria.min_sun_exposure_score is not None
        else "TRUE"
    )

    con.execute(f"""
        CREATE OR REPLACE TABLE matching_houses AS
        SELECT
            c.*,
            vs.has_lake_view,
            vs.lake_view_pct,
            vs.visible_lake,
            vs.dist_to_lake_m,
            vs.elevation_above_lake_m,
            vs.has_mountain_view,
            vs.mountain_view_score,
            vs.visible_peaks,
            vs.slope_aspect,
            vs.slope_aspect_deg,
            vs.sun_exposure_score,
            vs.is_south_facing
        FROM pre_viewshed_candidates c
        JOIN viewshed_scores vs ON c.egid = vs.egid
        WHERE ({lake_filter_sql})
          AND ({mountain_filter_sql})
          AND ({south_facing_sql})
          AND ({sun_score_sql});
    """)

    final_count = con.execute("SELECT count(*) FROM matching_houses").fetchone()[0]
    logger.info("Filtering complete. %d matching houses identified.", final_count)

    # 8. Export to GeoParquet and GeoJSON
    parquet_path = out_path / "matching_houses.parquet"
    geojson_path = out_path / "matching_houses.geojson"

    con.execute(f"""
        COPY matching_houses TO '{parquet_path}' (FORMAT PARQUET);
    """)
    logger.info("Exported Parquet: %s", parquet_path)

    # Export to GeoJSON FeatureCollection
    rows = con.execute("""
        SELECT
            egid, canton, municipality, municipality_id, street, house_number, postal_code, city,
            gkode, gkodn, lat, lon, gkat, gklas, house_type, num_dwellings, building_area_m2,
            estimated_living_area_m2, median_price_per_m2, estimated_price_chf, affordability_tier,
            ov_class, dist_to_transit_m, walk_time_transit_min,
            dist_to_restaurant_m, walk_time_restaurant_min, num_restaurants_nearby, num_cafes_nearby,
            nearest_supermarket, supermarket_brand, dist_to_supermarket_m, walk_time_supermarket_min,
            nearest_gym, gym_type, dist_to_gym_m, walk_time_gym_min,
            local_pop_density, estimated_garden_m2, green_ratio,
            dist_to_motorway_m, dist_to_railway_m, street_typology, quietness_score,
            nearest_transit_stop, transit_type, transit_cadence_min, nearest_big_city,
            transit_travel_time_min, total_commute_min,
            has_lake_view, lake_view_pct, visible_lake, dist_to_lake_m, elevation_above_lake_m,
            has_mountain_view, mountain_view_score, visible_peaks,
            nearest_airport, dist_to_airport_km, nearest_major_airport, dist_to_major_airport_km,
            nearest_school, dist_to_school_m, walk_time_school_min,
            nearest_daycare, dist_to_daycare_m, walk_time_daycare_min,
            transit_time_daycare_min, daycare_access_min, daycare_access_mode,
            in_hazard_zone, hazard_status,
            tax_multiplier_pct, tax_tier,
            dist_to_main_road_m, road_safety_score,
            slope_aspect, slope_aspect_deg, sun_exposure_score, is_south_facing,
            transit_hops, transit_route_desc
        FROM matching_houses;
    """).fetchall()

    def _to_json_val(val: Any) -> Any:
        if val is None:
            return None
        if hasattr(val, "as_tuple") or val.__class__.__name__ == "Decimal":
            return float(val)
        return val

    features = []
    for r in rows:
        lat_val = _to_json_val(r[10])
        lon_val = _to_json_val(r[11])
        sv_url = format_street_view_url(lat_val, lon_val) if lat_val is not None and lon_val is not None else None
        sv_html = format_street_view_html(lat_val, lon_val) if lat_val is not None and lon_val is not None else None

        feat = {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [lon_val, lat_val]  # lon, lat
            },
            "properties": {
                "egid": int(r[0]) if r[0] is not None else None,
                "canton": str(r[1]),
                "municipality": str(r[2]),
                "municipality_id": int(r[3]) if r[3] is not None else None,
                "street": str(r[4]),
                "house_number": str(r[5]),
                "postal_code": int(r[6]) if r[6] is not None else None,
                "city": str(r[7]),
                "street_view_url": sv_url,
                "google_street_view": sv_html,
                "gkode": _to_json_val(r[8]),
                "gkodn": _to_json_val(r[9]),
                "lat": lat_val,
                "lon": lon_val,
                "gkat": int(r[12]) if r[12] is not None else None,
                "gklas": int(r[13]) if r[13] is not None else None,
                "house_type": str(r[14]),
                "num_dwellings": int(r[15]) if r[15] is not None else None,
                "building_area_m2": _to_json_val(r[16]),
                "estimated_living_area_m2": _to_json_val(r[17]),
                "median_price_per_m2": _to_json_val(r[18]),
                "estimated_price_chf": _to_json_val(r[19]),
                "affordability_tier": str(r[20]),
                "ov_class": str(r[21]),
                "dist_to_transit_m": _to_json_val(r[22]),
                "walk_time_transit_min": _to_json_val(r[23]),
                "dist_to_restaurant_m": _to_json_val(r[24]),
                "walk_time_restaurant_min": _to_json_val(r[25]),
                "num_restaurants_nearby": int(r[26]) if r[26] is not None else 0,
                "num_cafes_nearby": int(r[27]) if r[27] is not None else 0,
                "nearest_supermarket": str(r[28]) if r[28] else None,
                "supermarket_brand": str(r[29]) if r[29] else None,
                "dist_to_supermarket_m": _to_json_val(r[30]),
                "walk_time_supermarket_min": _to_json_val(r[31]),
                "nearest_gym": str(r[32]) if r[32] else None,
                "gym_type": str(r[33]) if r[33] else None,
                "dist_to_gym_m": _to_json_val(r[34]),
                "walk_time_gym_min": _to_json_val(r[35]),
                "local_pop_density": _to_json_val(r[36]),
                "estimated_garden_m2": _to_json_val(r[37]),
                "green_ratio": _to_json_val(r[38]),
                "dist_to_motorway_m": _to_json_val(r[39]),
                "dist_to_railway_m": _to_json_val(r[40]),
                "street_typology": str(r[41]),
                "quietness_score": _to_json_val(r[42]),
                "nearest_transit_stop": str(r[43]) if r[43] else None,
                "transit_type": str(r[44]) if r[44] else None,
                "transit_cadence_min": _to_json_val(r[45]),
                "nearest_big_city": str(r[46]) if r[46] else None,
                "transit_travel_time_min": _to_json_val(r[47]),
                "total_commute_min": _to_json_val(r[48]),
                "has_lake_view": bool(r[49]) if r[49] is not None else False,
                "lake_view_pct": _to_json_val(r[50]),
                "visible_lake": str(r[51]) if r[51] else None,
                "dist_to_lake_m": _to_json_val(r[52]),
                "elevation_above_lake_m": _to_json_val(r[53]),
                "has_mountain_view": bool(r[54]) if r[54] is not None else False,
                "mountain_view_score": _to_json_val(r[55]),
                "visible_peaks": str(r[56]) if r[56] else None,
                "nearest_airport": str(r[57]) if r[57] else None,
                "dist_to_airport_km": _to_json_val(r[58]),
                "nearest_major_airport": str(r[59]) if r[59] else None,
                "dist_to_major_airport_km": _to_json_val(r[60]),
                "nearest_school": str(r[61]) if r[61] else None,
                "dist_to_school_m": _to_json_val(r[62]),
                "walk_time_school_min": _to_json_val(r[63]),
                "nearest_daycare": str(r[64]) if r[64] else None,
                "dist_to_daycare_m": _to_json_val(r[65]),
                "walk_time_daycare_min": _to_json_val(r[66]),
                "transit_time_daycare_min": _to_json_val(r[67]),
                "daycare_access_min": _to_json_val(r[68]),
                "daycare_access_mode": str(r[69]) if r[69] else None,
                "in_hazard_zone": bool(r[70]) if r[70] is not None else False,
                "hazard_status": str(r[71]) if r[71] else None,
                "tax_multiplier_pct": _to_json_val(r[72]),
                "tax_tier": str(r[73]) if r[73] else None,
                "dist_to_main_road_m": _to_json_val(r[74]),
                "road_safety_score": _to_json_val(r[75]),
                "slope_aspect": str(r[76]) if r[76] else None,
                "slope_aspect_deg": _to_json_val(r[77]),
                "sun_exposure_score": _to_json_val(r[78]),
                "is_south_facing": bool(r[79]) if r[79] is not None else False,
                "transit_hops": int(r[80]) if r[80] is not None else None,
                "transit_route_desc": str(r[81]) if r[81] else None,
            }
        }
        features.append(feat)

    geojson_doc = {
        "type": "FeatureCollection",
        "name": "matching_houses",
        "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}},
        "features": features,
    }

    with open(geojson_path, "w", encoding="utf-8") as f:
        json.dump(geojson_doc, f, indent=2, default=float)
    logger.info("Exported GeoJSON: %s (%d features)", geojson_path, len(features))

    return final_count


def run_pipeline(
    config: Dict[str, Any],
    **criteria_overrides: Any,
) -> int:
    """Run end-to-end pipeline from database using provided configuration and criteria."""
    storage = config.get("storage", {})
    db_path = storage.get("db_path", DEFAULT_DB_PATH)
    out_dir = storage.get("output_dir", "output")
    ext_dir = storage.get("extensions_dir", DEFAULT_EXT_DIR)

    criteria = HousingFilterCriteria.from_config(config, **criteria_overrides)
    con = get_duckdb_connection(db_path=db_path, extensions_dir=ext_dir)

    try:
        count = execute_housing_pipeline(con, criteria, output_dir=out_dir)
        return count
    finally:
        con.close()
