"""Unit tests for the Swiss Housing Discovery geospatial pipeline.

Verifies strict inclusion and exclusion of default criteria:
- Houses: standalone, dual-family, row houses
- With private garden (>= 100 m² and >= 35% green buffer)
- Walkability: <= 10 min walk (800m) to public transport AND restaurant
- Exclusions: commercial buildings, planned structures, dense urban flats without gardens,
  buildings without restaurants within 10 min, buildings without transit within 10 min.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Generator

import duckdb
import pytest

from ch_housing.density import (
    aggregate_to_h3,
    aggregate_to_metric_grid,
    build_interactive_density_map,
    detect_garden_enclaves,
    format_street_view_html,
    format_street_view_url,
    generate_density_layers,
    get_color_for_price,
)
from ch_housing.airports import SWISS_AIRPORTS
from ch_housing.download import load_config
from ch_housing.ingest import DEFAULT_EXT_DIR, get_duckdb_connection
from ch_housing.neighborhoods import (
    calculate_livability_score,
    discover_neighborhoods,
    export_neighborhoods,
)
from ch_housing.pipeline import HousingFilterCriteria, execute_housing_pipeline
from ch_housing.viewshed import (
    batch_evaluate_viewshed,
    evaluate_radial_viewshed,
    wgs84_to_lv95,
)


@pytest.fixture
def in_memory_spatial_con() -> Generator[duckdb.DuckDBPyConnection, None, None]:
    """Provide an in-memory DuckDB connection with spatial extension loaded."""
    con = get_duckdb_connection(db_path=":memory:", extensions_dir=DEFAULT_EXT_DIR)
    yield con
    con.close()


@pytest.fixture
def populated_test_db(in_memory_spatial_con: duckdb.DuckDBPyConnection) -> duckdb.DuckDBPyConnection:
    """Populate DuckDB with realistic synthetic Swiss LV95 (EPSG:2056) records."""
    con = in_memory_spatial_con

    # 1. Buildings Table (GWR / MADD)
    # Coordinates in Bern area (LV95: ~2600000, 1200000)
    con.execute("""
        CREATE OR REPLACE TABLE buildings AS
        SELECT * FROM (
            VALUES
                -- 1. Valid Standalone Single-Family House (Detached, existing, pure residential, Bern BE)
                (100101::BIGINT, 'BE', 'Bern', 351, 'Kramgasse', '12', 3011, 'Bern', 1004, 1020, 1110, 1, 120.0, 2600100.0, 1200100.0, ST_Point(2600100.0, 1200100.0)),

                -- 2. Commercial / Office Building (GKAT = 1060) -> MUST BE EXCLUDED
                (100102::BIGINT, 'BE', 'Bern', 351, 'Bahnhofplatz', '1', 3011, 'Bern', 1004, 1060, 1211, 0, 850.0, 2600200.0, 1200200.0, ST_Point(2600200.0, 1200200.0)),

                -- 3. Planned / Unbuilt House (GSTAT = 1001) -> MUST BE EXCLUDED
                (100103::BIGINT, 'BE', 'Bern', 351, 'Zukunftsweg', '5', 3011, 'Bern', 1001, 1020, 1110, 1, 110.0, 2600300.0, 1200300.0, ST_Point(2600300.0, 1200300.0)),

                -- 4. Demolished House (GSTAT = 1007) -> MUST BE EXCLUDED
                (100104::BIGINT, 'BE', 'Bern', 351, 'Altweg', '9', 3011, 'Bern', 1007, 1020, 1110, 1, 90.0, 2600400.0, 1200400.0, ST_Point(2600400.0, 1200400.0)),

                -- 5. Special Structure / Barn / Shed (GKAT = 1080) -> MUST BE EXCLUDED
                (100105::BIGINT, 'BE', 'Bern', 351, 'Scheunenweg', '2', 3011, 'Bern', 1004, 1080, 1271, 0, 200.0, 2600500.0, 1200500.0, ST_Point(2600500.0, 1200500.0)),

                -- 6. Large Multi-Family Apartment Complex (GKLAS = 1122, 16 dwellings) -> EXCLUDED
                (100106::BIGINT, 'BE', 'Bern', 351, 'Grossmattstrasse', '40', 3011, 'Bern', 1004, 1020, 1122, 16, 600.0, 2600600.0, 1200600.0, ST_Point(2600600.0, 1200600.0)),

                -- 7. Valid Dual-Family House (Zweifamilienhaus, GKLAS = 1121, 2 dwellings) -> INCLUDED BY DEFAULT
                (100107::BIGINT, 'ZH', 'Zürich', 261, 'Rudenzweg', '88', 8048, 'Zürich', 1004, 1020, 1121, 2, 100.0, 2683000.0, 1247000.0, ST_Point(2683000.0, 1247000.0)),

                -- 8. House in Low Transit Zone (No transit within 10 min / 800m) -> MUST BE EXCLUDED
                (100108::BIGINT, 'BE', 'Köniz', 355, 'Bergweg', '77', 3097, 'Liebefeld', 1004, 1020, 1110, 1, 100.0, 2605000.0, 1195000.0, ST_Point(2605000.0, 1195000.0)),

                -- 9. Dense Urban Flat with Zero Garden -> MUST BE EXCLUDED
                (100109::BIGINT, 'ZH', 'Zürich', 261, 'Betonweg', '3', 8001, 'Zürich', 1004, 1020, 1110, 1, 150.0, 2682000.0, 1248000.0, ST_Point(2682000.0, 1248000.0)),

                -- 10. House in Industrial Zone -> MUST BE EXCLUDED
                (100110::BIGINT, 'AG', 'Aarau', 4001, 'Industriestrasse', '50', 5000, 'Aarau', 1004, 1020, 1110, 1, 130.0, 2646000.0, 1249000.0, ST_Point(2646000.0, 1249000.0)),

                -- 11. Valid Row House (Reihenhaus, GKLAS=1110, 1 unit) -> INCLUDED BY DEFAULT
                (100111::BIGINT, 'ZH', 'Winterthur', 230, 'Reihenhausstrasse', '15', 8400, 'Winterthur', 1004, 1020, 1110, 1, 110.0, 2697000.0, 1261000.0, ST_Point(2697000.0, 1261000.0)),

                -- 12. Residential with Minor Commercial Secondary Use (GKAT = 1030)
                (100112::BIGINT, 'BE', 'Thun', 942, 'Dorfstrasse', '8', 3600, 'Thun', 1004, 1030, 1110, 1, 140.0, 2614000.0, 1178000.0, ST_Point(2614000.0, 1178000.0)),

                -- 13. House far from any Restaurant (> 800m / > 10 min) -> MUST BE EXCLUDED
                (100113::BIGINT, 'BE', 'Bern', 351, 'Waldeinsamkeit', '1', 3011, 'Bern', 1004, 1020, 1110, 1, 120.0, 2603000.0, 1203000.0, ST_Point(2603000.0, 1203000.0))
        ) AS t(egid, canton, municipality, municipality_id, street, house_number, postal_code, city, gstat, gkat, gklas, num_dwellings, building_area_m2, gkode, gkodn, geom);
    """)

    # 2. Public Transport Stops (BAV Haltestellen ÖV)
    con.execute("""
        CREATE OR REPLACE TABLE transit_stops AS
        SELECT * FROM (
            VALUES
                ('Bern, Kramgasse', 'Tram', 2600150.0, 1200120.0, ST_Point(2600150.0, 1200120.0)),      -- ~54m from 100101 (<1 min walk)
                ('Zürich, Seestrasse', 'Tram', 2683050.0, 1247020.0, ST_Point(2683050.0, 1247020.0)),   -- ~54m from 100107 (<1 min walk)
                ('Winterthur, Stadt', 'Bus', 2697050.0, 1261020.0, ST_Point(2697050.0, 1261020.0)),     -- ~54m from 100111 (<1 min walk)
                ('Thun, Dorf', 'Bus', 2614050.0, 1178020.0, ST_Point(2614050.0, 1178020.0)),            -- ~54m from 100112 (<1 min walk)
                ('Bern, Waldhaltestelle', 'Bus', 2602950.0, 1202950.0, ST_Point(2602950.0, 1202950.0))  -- Close to 100113 transit, but no restaurant!
        ) AS t(name, transit_type, gkode, gkodn, geom);
    """)

    # 3. Transit Quality (ARE ÖV-Güteklassen)
    con.execute("""
        CREATE OR REPLACE TABLE transit_quality AS
        SELECT * FROM (
            VALUES
                ('B', ST_Buffer(ST_Point(2600100.0, 1200100.0), 1000.0)),  -- Covers Bern 100101
                ('A', ST_Buffer(ST_Point(2683000.0, 1247000.0), 1500.0)),  -- Covers Zurich 100107
                ('B', ST_Buffer(ST_Point(2646000.0, 1249000.0), 1000.0)),  -- Covers Aarau 100110
                ('B', ST_Buffer(ST_Point(2697000.0, 1261000.0), 1000.0)),  -- Covers Winterthur 100111
                ('C', ST_Buffer(ST_Point(2614000.0, 1178000.0), 1000.0)),  -- Covers Thun 100112
                ('B', ST_Buffer(ST_Point(2603000.0, 1203000.0), 1000.0)),  -- Covers 100113
                ('D', ST_Buffer(ST_Point(2605000.0, 1195000.0), 200.0))    -- Low transit Class D for Köniz 100108
        ) AS t(ov_class, geom);
    """)

    # 4. Restaurants & Gastronomy Locations
    # Placed within 150-300m of valid houses (2-4 min walk)
    con.execute("""
        CREATE OR REPLACE TABLE restaurants AS
        SELECT * FROM (
            VALUES
                (1, 'Restaurant Bern', 'Kramgasse', '1', 'Bern', 2600200.0, 1200100.0, ST_Point(2600200.0, 1200100.0)),    -- 100m from 100101 (1.3 min walk)
                (2, 'Seerestaurant ZH', 'Seestrasse', '80', 'Zürich', 2683100.0, 1247000.0, ST_Point(2683100.0, 1247000.0)), -- 100m from 100107 (1.3 min walk)
                (3, 'Winti Bistro', 'Stadtweg', '5', 'Winterthur', 2697100.0, 1261000.0, ST_Point(2697100.0, 1261000.0)),  -- 100m from 100111 (1.3 min walk)
                (4, 'Gasthof Thun', 'Dorfplatz', '2', 'Thun', 2614100.0, 1178000.0, ST_Point(2614100.0, 1178000.0))         -- 100m from 100112 (1.3 min walk)
                -- Notice: NO restaurant within 800m of 100113 (nearest is > 2.8 km away)
        ) AS t(id, name, street, house_number, city, gkode, gkodn, geom);
    """)

    # 4b. Supermarkets & Grocery Stores (Migros, Coop, Denner, Volg)
    # Placed within 150-300m of valid houses (2-4 min walk)
    con.execute("""
        CREATE OR REPLACE TABLE supermarkets AS
        SELECT * FROM (
            VALUES
                (1, 'Migros Supermarkt Bern', 'Migros', 'supermarket', 'Kramgasse', '20', 3011, 'Bern', 'BE', 2600220.0, 1200100.0, ST_Point(2600220.0, 1200100.0)),
                (2, 'Coop Supermarkt Altstetten', 'Coop', 'supermarket', 'Rudenzweg', '10', 8048, 'Zürich', 'ZH', 2683120.0, 1247000.0, ST_Point(2683120.0, 1247000.0)),
                (3, 'Denner Filiale Winterthur', 'Denner', 'supermarket', 'Stadtweg', '12', 8400, 'Winterthur', 'ZH', 2697120.0, 1261000.0, ST_Point(2697120.0, 1261000.0)),
                (4, 'Volg Dorfladen Thun', 'Volg', 'supermarket', 'Dorfplatz', '5', 3600, 'Thun', 'BE', 2614120.0, 1178000.0, ST_Point(2614120.0, 1178000.0))
        ) AS t(id, name, brand, shop_type, street, house_number, postal_code, city, canton, gkode, gkodn, geom);
    """)

    # 4c. Gyms & Sports Facilities Table (Fitness, Sporthallen, Boulder)
    # Placed within 200-500m of valid houses (3-6 min walk, well within 20 min / 1600m)
    con.execute("""
        CREATE OR REPLACE TABLE gyms AS
        SELECT * FROM (
            VALUES
                (1, 'Fitnesspark Bern City', 'gym', 'Aarbergergasse', '30', 3011, 'Bern', 'BE', 2600250.0, 1200150.0, ST_Point(2600250.0, 1200150.0)),
                (2, 'PureGym Zürich Altstetten', 'gym', 'Hohlstrasse', '500', 8048, 'Zürich', 'ZH', 2683150.0, 1247050.0, ST_Point(2683150.0, 1247050.0)),
                (3, 'Sporthalle Winterthur', 'sports_hall', 'Grüzenstrasse', '10', 8400, 'Winterthur', 'ZH', 2697150.0, 1261050.0, ST_Point(2697150.0, 1261050.0)),
                (4, 'Sportzentrum Thun', 'sports_centre', 'Allmendstrasse', '5', 3600, 'Thun', 'BE', 2614150.0, 1178050.0, ST_Point(2614150.0, 1178050.0)),
                (5, 'Fitnessclub Küsnacht', 'gym', 'Seestrasse', '80', 8700, 'Küsnacht ZH', 'ZH', 2686150.0, 1242100.0, ST_Point(2686150.0, 1242100.0)),
                (6, 'Sporthalle Kloten', 'sports_hall', 'Schulstrasse', '12', 8302, 'Kloten', 'ZH', 2684080.0, 1254050.0, ST_Point(2684080.0, 1254050.0)),
                (7, 'Fitness Muri', 'gym', 'Thunstrasse', '20', 3074, 'Muri', 'BE', 2608150.0, 1192100.0, ST_Point(2608150.0, 1192100.0))
        ) AS t(id, name, gym_type, street, house_number, postal_code, city, canton, gkode, gkodn, geom);
    """)

    con.execute("CREATE INDEX IF NOT EXISTS idx_gyms_coords ON gyms(gkode, gkodn);")

    # 5. Population Density (STATPOP 100m grid)
    con.execute("""
        CREATE OR REPLACE TABLE population_density AS
        SELECT * FROM (
            VALUES
                (2600100::BIGINT, 1200100::BIGINT, 35.0, ST_Point(2600100.0, 1200100.0)),
                (2683000::BIGINT, 1247000::BIGINT, 45.0, ST_Point(2683000.0, 1247000.0)),
                (2697000::BIGINT, 1261000::BIGINT, 20.0, ST_Point(2697000.0, 1261000.0)),
                (2614000::BIGINT, 1178000::BIGINT, 28.0, ST_Point(2614000.0, 1178000.0)),
                (2603000::BIGINT, 1203000::BIGINT, 15.0, ST_Point(2603000.0, 1203000.0)),
                (2605000::BIGINT, 1195000::BIGINT, 5.0, ST_Point(2605000.0, 1195000.0)),
                (2682000::BIGINT, 1248000::BIGINT, 180.0, ST_Point(2682000.0, 1248000.0))
        ) AS t(grid_x, grid_y, population, geom);
    """)

    # 6. Building Zones (ARE Bauzonen)
    con.execute("""
        CREATE OR REPLACE TABLE building_zones AS
        SELECT * FROM (
            VALUES
                (11, 'Wohnzone', ST_Buffer(ST_Point(2600100.0, 1200100.0), 1000.0)),
                (11, 'Wohnzone', ST_Buffer(ST_Point(2683000.0, 1247000.0), 1000.0)),
                (11, 'Wohnzone', ST_Buffer(ST_Point(2697000.0, 1261000.0), 1000.0)),
                (11, 'Wohnzone', ST_Buffer(ST_Point(2614000.0, 1178000.0), 1000.0)),
                (11, 'Wohnzone', ST_Buffer(ST_Point(2603000.0, 1203000.0), 1000.0)),
                (11, 'Wohnzone', ST_Buffer(ST_Point(2605000.0, 1195000.0), 500.0)),
                (11, 'Wohnzone', ST_Buffer(ST_Point(2682000.0, 1248000.0), 500.0)),
                (13, 'Arbeitszone Industrie', ST_Buffer(ST_Point(2646000.0, 1249000.0), 500.0))
        ) AS t(zone_code, zone_name, geom);
    """)

    # 7. Land Cover Green Surfaces (swissTLM3D / Arealstatistik)
    con.execute("""
        CREATE OR REPLACE TABLE land_cover_green AS
        SELECT * FROM (
            VALUES
                (ST_Buffer(ST_Point(2600100.0, 1200100.0), 50.0)),  -- Green park/gardens around 100101
                (ST_Buffer(ST_Point(2683000.0, 1247000.0), 40.0)),  -- Green buffer around 100107
                (ST_Buffer(ST_Point(2697000.0, 1261000.0), 40.0)),  -- Green buffer around 100111
                (ST_Buffer(ST_Point(2614000.0, 1178000.0), 45.0)),  -- Green buffer around 100112
                (ST_Buffer(ST_Point(2603000.0, 1203000.0), 50.0)),  -- Green buffer around 100113
                (ST_Buffer(ST_Point(2605000.0, 1195000.0), 50.0))   -- Green buffer around 100108
        ) AS t(geom);
    """)

    # 8. Cantonal Cadastral Override Table
    con.execute("""
        CREATE OR REPLACE TABLE canton_cadastral_gardens (
            egid BIGINT,
            garden_m2 DOUBLE,
            geom GEOMETRY
        );
    """)

    return con


def test_default_criteria_matches_standalone_dual_family_and_row(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify default criteria matches standalone (100101), dual-family (100107), and row houses (100111)."""
    criteria = HousingFilterCriteria()  # Default criteria
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100101 in egids, "Standalone single-family house (100101) must be included by default!"
    assert 100107 in egids, "Dual-family house (100107) must be included by default!"
    assert 100111 in egids, "Row house (100111) must be included by default!"


def test_commercial_building_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify commercial office building (GKAT=1060) is strictly excluded."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100102 not in egids, "Commercial building (GKAT=1060) must be excluded!"


def test_planned_and_demolished_buildings_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify non-existing buildings (GSTAT!=1004) are excluded."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100103 not in egids, "Planned building (GSTAT=1001) must be excluded!"
    assert 100104 not in egids, "Demolished building (GSTAT=1007) must be excluded!"


def test_dense_apartment_blocks_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify large apartment building (16 units) is excluded by default (max_units=2)."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100106 not in egids, "Large multi-family apartment building (16 units) must be excluded!"


def test_house_without_restaurant_within_10min_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify house with no restaurant within 10 min walking (800m) is excluded."""
    criteria = HousingFilterCriteria(max_restaurant_walk_min=10.0, max_restaurant_dist_m=800.0)
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100113 not in egids, "House 100113 with no restaurant within 10 min walk must be excluded!"


def test_house_without_transit_within_10min_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify house with no transit within 10 min walking (800m) is excluded."""
    criteria = HousingFilterCriteria(max_transit_walk_min=10.0, max_transit_dist_m=800.0)
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100108 not in egids, "House 100108 with no transit stop within 10 min walk must be excluded!"


def test_zero_garden_urban_flat_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify buildings with sealed surroundings and zero green garden are excluded."""
    criteria = HousingFilterCriteria(min_garden_m2=100.0, min_green_ratio=0.35)
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100109 not in egids, "Building with no green garden must be excluded by garden thresholds!"


def test_industrial_zone_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify buildings sitting outside residential zones (e.g. industrial Arbeitszone) are excluded."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100110 not in egids, "Building in industrial zone (Arbeitszone) must be excluded!"


def test_walk_times_and_distances_computed(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify distance and walk times to transit, restaurant, and supermarket are computed and <= 10 min."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    rows = populated_test_db.execute("""
        SELECT egid, house_type, dist_to_transit_m, walk_time_transit_min,
               dist_to_restaurant_m, walk_time_restaurant_min,
               dist_to_supermarket_m, walk_time_supermarket_min
        FROM matching_houses;
    """).fetchall()

    assert len(rows) >= 3
    for egid, htype, dist_tr, walk_tr, dist_rst, walk_rst, dist_sm, walk_sm in rows:
        assert dist_tr <= 800.0, f"Transit distance {dist_tr}m exceeds 800m for EGID {egid}"
        assert walk_tr <= 10.0, f"Transit walk time {walk_tr} min exceeds 10 min for EGID {egid}"
        assert dist_rst <= 800.0, f"Restaurant distance {dist_rst}m exceeds 800m for EGID {egid}"
        assert walk_rst <= 10.0, f"Restaurant walk time {walk_rst} min exceeds 10 min for EGID {egid}"
        assert dist_sm <= 800.0, f"Supermarket distance {dist_sm}m exceeds 800m for EGID {egid}"
        assert walk_sm <= 10.0, f"Supermarket walk time {walk_sm} min exceeds 10 min for EGID {egid}"
        assert htype in ("standalone", "dual-family", "row", "standalone/row")


def test_mixed_use_toggle(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify include_mixed_use flag controls inclusion of GKAT 1030 (secondary residential)."""
    criteria_pure = HousingFilterCriteria(include_mixed_use=False)
    execute_housing_pipeline(populated_test_db, criteria_pure, output_dir=tmp_path)
    egids_pure = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100112 not in egids_pure, "Secondary residential (GKAT=1030) must be excluded when pure residential only!"

    criteria_mixed = HousingFilterCriteria(include_mixed_use=True)
    execute_housing_pipeline(populated_test_db, criteria_mixed, output_dir=tmp_path)
    egids_mixed = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100112 in egids_mixed, "Secondary residential (GKAT=1030) must be included when include_mixed_use=True!"


def test_density_map_export(tmp_path: Path):
    """Verify Folium interactive HTML map exports cleanly with swisstopo OGD tiles."""
    sample_houses = [
        {"egid": 1, "street": "Marktgasse", "house_number": "1", "postal_code": 3011, "city": "Bern", "canton": "BE", "lat": 46.951, "lon": 7.438, "house_type": "standalone", "estimated_garden_m2": 220.0, "green_ratio": 0.45, "ov_class": "B", "dist_to_transit_m": 120.0, "walk_time_transit_min": 1.5, "dist_to_restaurant_m": 180.0, "walk_time_restaurant_min": 2.3, "local_pop_density": 25.0, "num_dwellings": 1, "building_area_m2": 110.0},
        {"egid": 2, "street": "Seestrasse", "house_number": "5", "postal_code": 8001, "city": "Zürich", "canton": "ZH", "lat": 47.370, "lon": 8.544, "house_type": "dual-family", "estimated_garden_m2": 180.0, "green_ratio": 0.40, "ov_class": "A", "dist_to_transit_m": 80.0, "walk_time_transit_min": 1.0, "dist_to_restaurant_m": 250.0, "walk_time_restaurant_min": 3.1, "local_pop_density": 40.0, "num_dwellings": 2, "building_area_m2": 130.0},
    ]

    html_file = tmp_path / "density_map.html"
    res = build_interactive_density_map(
        sample_houses,
        output_html_path=html_file,
        h3_resolution=7,
        default_basemap="swisstopo-gray",
    )
    assert html_file.exists()
    assert html_file.stat().st_size > 500

    content = html_file.read_text(encoding="utf-8")
    assert "Swiss Private Housing Map" in content
    assert "swisstopo" in content.lower()
    assert "wmts.geo.admin.ch" in content


def test_swisstopo_gray_sole_basemap_and_selector_removed(tmp_path: Path):
    """Verify that Swisstopo Gray is the sole basemap and selector is removed by default."""
    sample_houses = [
        {"egid": 1, "street": "Marktgasse", "house_number": "1", "postal_code": 3011, "city": "Bern", "canton": "BE", "lat": 46.951, "lon": 7.438, "house_type": "standalone", "estimated_garden_m2": 220.0, "green_ratio": 0.45, "ov_class": "B", "dist_to_transit_m": 120.0, "walk_time_transit_min": 1.5, "dist_to_restaurant_m": 180.0, "walk_time_restaurant_min": 2.3, "local_pop_density": 25.0, "num_dwellings": 1, "building_area_m2": 110.0},
    ]

    # 1. Default (include_selector=False): Sole basemap Swisstopo Gray, NO selector
    default_map = tmp_path / "default_map.html"
    build_interactive_density_map(sample_houses, output_html_path=default_map, include_selector=False)
    assert default_map.exists()
    content = default_map.read_text(encoding="utf-8")

    # Verify ONLY Swisstopo Gray is included
    assert "ch.swisstopo.pixelkarte-grau" in content
    assert "ch.swisstopo.pixelkarte-farbe" not in content
    assert "ch.swisstopo.swissimage" not in content
    assert "cartocdn.com" not in content
    assert "tile.openstreetmap.org" not in content

    # Verify selector (L.control.layers) is NOT present
    assert "L.control.layers" not in content

    # 2. When include_selector=True: layer control present but NO basemap selector radio buttons
    selector_map = tmp_path / "selector_map.html"
    build_interactive_density_map(sample_houses, output_html_path=selector_map, include_selector=True)
    assert selector_map.exists()
    sel_content = selector_map.read_text(encoding="utf-8")
    assert "L.control.layers" in sel_content
    # base_layers must be empty (no basemap switcher)
    assert "base_layers : {\n                }" in sel_content or "base_layers : {}" in sel_content.replace(" ", "")


def test_tile_usage_policy_compliance():
    """Verify that tile usage complies with OpenStreetMap and official Swiss OGD policies."""
    from ch_housing.density import BASEMAP_CONFIGS

    assert "swisstopo-gray" in BASEMAP_CONFIGS
    assert "wmts.geo.admin.ch" in BASEMAP_CONFIGS["swisstopo-gray"]["tiles"]
    assert "swisstopo" in BASEMAP_CONFIGS["swisstopo-gray"]["attr"].lower()

    for name, cfg in BASEMAP_CONFIGS.items():
        assert "attr" in cfg and cfg["attr"], f"Basemap {name} missing attribution!"
        assert "tiles" in cfg and cfg["tiles"], f"Basemap {name} missing tiles URL!"

    osm_cfg = BASEMAP_CONFIGS.get("openstreetmap", {})
    assert "OpenStreetMap" in osm_cfg.get("attr", "")
    assert "openstreetmap.org/copyright" in osm_cfg.get("attr", "")


def test_cli_runner(tmp_path: Path):
    """Verify Typer CLI query and map execution via CliRunner."""
    from typer.testing import CliRunner
    from ch_housing.cli import app

    runner = CliRunner()
    result = runner.invoke(app, ["--help"])
    assert result.exit_code == 0
    assert "ch-housing" in result.output

    q_result = runner.invoke(app, ["query", "--help"], env={"COLUMNS": "160"})
    assert q_result.exit_code == 0
    assert "--max-transit-walk-min" in q_result.output
    assert "--max-restaurant-walk-min" in q_result.output
    assert "--min-garden-m2" in q_result.output
    assert "--exclude-arterial" in q_result.output
    assert "--min-quietness-score" in q_result.output
    assert "--calm-lanes-only" in q_result.output
    assert "--max-price" in q_result.output


def test_config_loader():
    """Verify loading and parsing of config.default.yaml."""
    cfg = load_config("config.default.yaml")
    assert "filters" in cfg
    filters = cfg["filters"]
    assert filters["building_type"] == "house"
    assert filters["max_units"] == 2
    assert filters["min_garden_m2"] == 100.0
    assert filters["max_transit_walk_min"] == 10.0
    assert filters["max_transit_dist_m"] == 800.0
    assert filters["max_restaurant_walk_min"] == 10.0
    assert filters["max_restaurant_dist_m"] == 800.0
    assert filters["exclude_arterial_streets"] is True
    assert filters["min_motorway_dist_m"] == 200.0
    assert filters["min_railway_dist_m"] == 100.0
    assert filters["min_quietness_score"] == 65.0
    assert filters["calm_lanes_only"] is False
    assert filters["max_price_chf"] == 3000000.0
    assert cfg["datasets"]["land_cover"]["filename"] == "arealstatistik_2056.gpkg"


def test_extract_archive_sqlite_misnamed_as_zip(tmp_path: Path):
    """Verify that uncompressed SQLite/GeoPackage files misnamed as .zip are normalized to .gpkg without BadZipFile."""
    import sqlite3
    from ch_housing.download import extract_archive

    misnamed_zip = tmp_path / "arealstatistik_2056.csv.zip"
    con = sqlite3.connect(str(misnamed_zip))
    con.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);")
    con.commit()
    con.close()

    # extract_archive should detect SQLite header, rename to .gpkg, and not crash
    results = extract_archive(misnamed_zip, tmp_path)
    assert len(results) == 1
    assert results[0].suffix == ".gpkg"
    assert results[0].exists()
    assert not misnamed_zip.exists()


def test_arealstatistik_gpkg_ingestion(tmp_path: Path):
    """Verify ingestion of Arealstatistik GeoPackage with AS classification."""
    import sqlite3
    from ch_housing.ingest import get_duckdb_connection, ingest_land_cover

    gpkg_file = tmp_path / "arealstatistik_2056.gpkg"
    scon = sqlite3.connect(str(gpkg_file))
    scon.execute("PRAGMA application_id = 0x47504b47;")
    scon.executescript("""
        CREATE TABLE gpkg_spatial_ref_sys (
            srs_name TEXT NOT NULL, srs_id INTEGER NOT NULL PRIMARY KEY, organization TEXT NOT NULL, organization_coordsys_id INTEGER NOT NULL, definition TEXT NOT NULL, description TEXT
        );
        CREATE TABLE gpkg_contents (
            table_name TEXT NOT NULL PRIMARY KEY, data_type TEXT NOT NULL, identifier TEXT, description TEXT, last_change TEXT, min_x DOUBLE, min_y DOUBLE, max_x DOUBLE, max_y DOUBLE, srs_id INTEGER
        );
        CREATE TABLE gpkg_geometry_columns (
            table_name TEXT NOT NULL, column_name TEXT NOT NULL, geometry_type_name TEXT NOT NULL, srs_id INTEGER NOT NULL, z TINYINT NOT NULL, m TINYINT NOT NULL
        );
        INSERT INTO gpkg_spatial_ref_sys VALUES ('CH1903+ / LV95', 2056, 'EPSG', 2056, '', '');
        INSERT INTO gpkg_contents VALUES ('arealstatistik_all', 'features', 'arealstatistik_all', '', '', 2600000, 1199000, 2601000, 1200000, 2056);
        INSERT INTO gpkg_geometry_columns VALUES ('arealstatistik_all', 'geom', 'POINT', 2056, 0, 0);

        CREATE TABLE arealstatistik_all (
            fid INTEGER PRIMARY KEY,
            geom BLOB,
            E_COORD DOUBLE,
            N_COORD DOUBLE,
            AS18_72 INTEGER,
            AS25_72 INTEGER
        );
        -- Insert green (12 = Hausgärten, 4 = Gebäude mit Umschwung) and non-green (41 = Wald)
        INSERT INTO arealstatistik_all VALUES (1, NULL, 2600100.0, 1199100.0, 12, NULL);
        INSERT INTO arealstatistik_all VALUES (2, NULL, 2600200.0, 1199200.0, 4, 4);
        INSERT INTO arealstatistik_all VALUES (3, NULL, 2600300.0, 1199300.0, 41, 41);
    """)
    scon.commit()
    scon.close()

    dcon = get_duckdb_connection(":memory:")
    count = ingest_land_cover(dcon, tmp_path)
    assert count == 2  # Only the 2 green records
    res = dcon.execute("SELECT count(*) FROM land_cover_green").fetchone()[0]
    assert res == 2


def test_detect_garden_enclaves():
    """Verify detection and aggregation of small garden enclaves (5-100 houses)."""
    from ch_housing.density import detect_garden_enclaves

    # Create 8 houses clustered in Altstetten (Rudenzweg)
    sample_cluster = [
        {
            "egid": 100 + i,
            "street": "Rudenzweg",
            "house_number": str(i * 2),
            "postal_code": 8048,
            "city": "Zürich",
            "canton": "ZH",
            "lat": 47.38507 + (i * 0.00005),
            "lon": 8.49748 + (i * 0.00005),
            "estimated_garden_m2": 450.0 + (i * 10),
            "green_ratio": 0.55,
            "walk_time_transit_min": 2.5,
            "walk_time_restaurant_min": 4.0,
            "building_area_m2": 52.0,
        }
        for i in range(8)
    ]

    enclaves = detect_garden_enclaves(sample_cluster, min_houses=5, max_houses=100, resolution=9)
    assert len(enclaves) == 1
    props = enclaves[0]["properties"]
    assert props["house_count"] == 8
    assert "8048 Zürich" in props["enclave_label"]
    assert "Rudenzweg" in props["top_streets"]
    assert props["median_garden_m2"] > 400.0
    assert props["median_walk_transit_min"] == 2.5
    assert props["median_quietness_score"] >= 90.0


def test_arterial_street_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify houses located on arterial streets (e.g. Hauptstrasse, Kantonsstrasse) are excluded when exclude_arterial_streets=True."""
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100114, 'BE', 'Bern', 351, 'Hauptstrasse', '10', 3011, 'Bern', 1004, 1020, 1110, 1, 120.0, 2600110.0, 1200110.0, ST_Point(2600110.0, 1200110.0));
    """)
    # With exclude_arterial_streets=True (default)
    criteria = HousingFilterCriteria(exclude_arterial_streets=True)
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)
    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100114 not in egids, "House on Hauptstrasse must be excluded when exclude_arterial_streets=True!"

    # With exclude_arterial_streets=False
    criteria_allow = HousingFilterCriteria(exclude_arterial_streets=False, min_quietness_score=0.0)
    execute_housing_pipeline(populated_test_db, criteria_allow, output_dir=tmp_path)
    egids_allow = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100114 in egids_allow, "House on Hauptstrasse must be included when exclude_arterial_streets=False!"


def test_motorway_and_railway_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify motorway and railway proximity filters exclude noisy houses."""
    # Create motorway and railway corridor tables
    populated_test_db.execute("""
        CREATE OR REPLACE TABLE motorway_corridors AS
        SELECT 1 AS fid, 2600100.0 AS gkode, 1200200.0 AS gkodn, ST_Point(2600100.0, 1200200.0) AS geom;
        CREATE OR REPLACE TABLE railway_corridors AS
        SELECT 1 AS fid, 2683000.0 AS gkode, 1247050.0 AS gkodn, ST_Point(2683000.0, 1247050.0) AS geom;
    """)

    # House 100101 is at (2600100, 1200100), distance to motorway is 100m (< min_motorway_dist_m=200m)
    # House 100107 is at (2683000, 1247000), distance to railway is 50m (< min_railway_dist_m=100m)
    criteria = HousingFilterCriteria(min_motorway_dist_m=200.0, min_railway_dist_m=100.0)
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100101 not in egids, "House 100101 within 100m of motorway must be excluded!"
    assert 100107 not in egids, "House 100107 within 50m of railway must be excluded!"
    # House 100111 is at (2697000, 1261000) which is far from both, so it should be included
    assert 100111 in egids, "Quiet house 100111 away from corridors should remain included!"


def test_street_typology_and_quietness_scoring(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify street typology tagging (calm_lane, residential) and quietness score computation."""
    # Insert house on a calm lane (e.g. Gladiolenweg)
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100115, 'ZH', 'Zürich', 261, 'Gladiolenweg', '21', 8048, 'Zürich', 1004, 1020, 1110, 1, 100.0, 2697010.0, 1261010.0, ST_Point(2697010.0, 1261010.0));
    """)
    criteria = HousingFilterCriteria(calm_lanes_only=True)
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    rows = populated_test_db.execute("""
        SELECT egid, street, street_typology, quietness_score FROM matching_houses;
    """).fetchall()

    assert len(rows) >= 1
    for egid, street, typology, qscore in rows:
        assert typology == "calm_lane"
        assert qscore >= 90.0


def test_price_budget_ceiling_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify houses exceeding the maximum budget ceiling (e.g. 3M CHF) are excluded."""
    # Insert luxury mansion in Küsnacht (8700, 24,000 CHF/m², 200m² footprint = 300m² living area = 7.2M CHF)
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100116, 'ZH', 'Küsnacht (ZH)', 154, 'Goldküstenstrasse', '1', 8700, 'Küsnacht', 1004, 1020, 1110, 1, 200.0, 2697010.0, 1261010.0, ST_Point(2697010.0, 1261010.0));
    """)

    # With max_price_chf = 3000000 (default)
    criteria_3m = HousingFilterCriteria(max_price_chf=3000000.0)
    execute_housing_pipeline(populated_test_db, criteria_3m, output_dir=tmp_path)
    egids_3m = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100116 not in egids_3m, "Luxury house exceeding 3M CHF must be excluded!"

    # With max_price_chf = None
    criteria_unlimited = HousingFilterCriteria(max_price_chf=None)
    execute_housing_pipeline(populated_test_db, criteria_unlimited, output_dir=tmp_path)
    egids_unlimited = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100116 in egids_unlimited, "House must be included when max_price_chf is unlimited!"


def test_transit_cadence_filter(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify houses with infrequent transit (cadence > 15 min, e.g. 30m or 60 min bus) are excluded."""
    # Insert pure residential house in Thun (100117, GKAT=1020)
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100117, 'BE', 'Thun', 942, 'Gartenstrasse', '5', 3600, 'Thun', 1004, 1020, 1110, 1, 120.0, 2614000.0, 1178000.0, ST_Point(2614000.0, 1178000.0));
    """)

    # Update transit_stops with cadence and commute columns
    populated_test_db.execute("""
        CREATE OR REPLACE TABLE transit_stops AS
        SELECT * FROM (
            VALUES
                ('Bern, Kramgasse', 'Tram', 2600150.0, 1200120.0, ST_Point(2600150.0, 1200120.0), 5.0, 'Bern', 3.0),
                ('Zürich, Seestrasse', 'Tram', 2683050.0, 1247020.0, ST_Point(2683050.0, 1247020.0), 6.0, 'Zürich', 4.0),
                ('Winterthur, Stadt', 'Bus', 2697050.0, 1261020.0, ST_Point(2697050.0, 1261020.0), 7.5, 'Winterthur', 3.0),
                ('Thun, Dorf', 'Bus', 2614050.0, 1178020.0, ST_Point(2614050.0, 1178020.0), 30.0, 'Bern', 19.0), -- 30 min cadence bus (> 15 min limit)
                ('Bern, Waldhaltestelle', 'Bus', 2602950.0, 1202950.0, ST_Point(2602950.0, 1202950.0), 15.0, 'Bern', 12.0)
        ) AS t(name, transit_type, gkode, gkodn, geom, cadence_min, nearest_big_city, transit_travel_time_min);
    """)

    # With default max_transit_cadence_min = 15.0, Thun house (100117) served by 30 min bus must be excluded
    criteria_15 = HousingFilterCriteria(max_transit_cadence_min=15.0)
    execute_housing_pipeline(populated_test_db, criteria_15, output_dir=tmp_path)
    egids_15 = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100117 not in egids_15, "House 100117 served by 30-min bus must be excluded with 15m cadence limit!"

    # With max_transit_cadence_min = 60.0, Thun house should be included
    criteria_60 = HousingFilterCriteria(max_transit_cadence_min=60.0)
    execute_housing_pipeline(populated_test_db, criteria_60, output_dir=tmp_path)
    egids_60 = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100117 in egids_60, "House 100117 should be included when cadence threshold is relaxed to 60m!"


def test_big_city_commute_time_filter(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify houses with transit commute to big city > 25 min are excluded."""
    # Insert pure residential house in Thun (100117, GKAT=1020)
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100117, 'BE', 'Thun', 942, 'Gartenstrasse', '5', 3600, 'Thun', 1004, 1020, 1110, 1, 120.0, 2614000.0, 1178000.0, ST_Point(2614000.0, 1178000.0));
    """)

    # Set Thun commute to 35 min (> 25 min)
    populated_test_db.execute("""
        CREATE OR REPLACE TABLE transit_stops AS
        SELECT * FROM (
            VALUES
                ('Bern, Kramgasse', 'Tram', 2600150.0, 1200120.0, ST_Point(2600150.0, 1200120.0), 5.0, 'Bern', 3.0),
                ('Zürich, Seestrasse', 'Tram', 2683050.0, 1247020.0, ST_Point(2683050.0, 1247020.0), 6.0, 'Zürich', 4.0),
                ('Winterthur, Stadt', 'Bus', 2697050.0, 1261020.0, ST_Point(2697050.0, 1261020.0), 7.5, 'Winterthur', 3.0),
                ('Thun, Dorf', 'Bus', 2614050.0, 1178020.0, ST_Point(2614050.0, 1178020.0), 15.0, 'Bern', 35.0), -- 35 min commute (> 25 min)
                ('Bern, Waldhaltestelle', 'Bus', 2602950.0, 1202950.0, ST_Point(2602950.0, 1202950.0), 15.0, 'Bern', 12.0)
        ) AS t(name, transit_type, gkode, gkodn, geom, cadence_min, nearest_big_city, transit_travel_time_min);
    """)

    # Default max_commute_time_min = 25.0
    criteria_25 = HousingFilterCriteria(max_commute_time_min=25.0)
    execute_housing_pipeline(populated_test_db, criteria_25, output_dir=tmp_path)
    egids_25 = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100117 not in egids_25, "House 100117 with 35 min commute must be excluded by 25 min limit!"

    # Relaxed max_commute_time_min = 40.0
    criteria_40 = HousingFilterCriteria(max_commute_time_min=40.0)
    execute_housing_pipeline(populated_test_db, criteria_40, output_dir=tmp_path)
    egids_40 = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100117 in egids_40, "House 100117 should be included when commute limit is 40 min!"


def test_commute_target_city_filter(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify filtering for commute to a specific city (e.g. Zürich only)."""
    populated_test_db.execute("""
        CREATE OR REPLACE TABLE transit_stops (
            name VARCHAR,
            transit_type VARCHAR,
            gkode DOUBLE,
            gkodn DOUBLE,
            geom GEOMETRY,
            cadence_min DOUBLE,
            nearest_big_city VARCHAR,
            transit_travel_time_min DOUBLE
        );
        INSERT INTO transit_stops VALUES
            ('Bern, Kramgasse', 'Tram', 2600150.0, 1200120.0, ST_Point(2600150.0, 1200120.0), 5.0, 'Bern', 3.0),
            ('Zürich, Seestrasse', 'Tram', 2683050.0, 1247020.0, ST_Point(2683050.0, 1247020.0), 6.0, 'Zürich', 4.0),
            ('Winterthur, Stadt', 'Bus', 2697050.0, 1261020.0, ST_Point(2697050.0, 1261020.0), 7.5, 'Winterthur', 3.0),
            ('Thun, Dorf', 'Bus', 2614050.0, 1178020.0, ST_Point(2614050.0, 1178020.0), 15.0, 'Bern', 19.0),
            ('Bern, Waldhaltestelle', 'Bus', 2602950.0, 1202950.0, ST_Point(2602950.0, 1202950.0), 15.0, 'Bern', 12.0);
    """)

    # Restrict to Zürich commute only
    criteria_zh = HousingFilterCriteria(commute_target_city="Zürich")
    execute_housing_pipeline(populated_test_db, criteria_zh, output_dir=tmp_path)
    egids_zh = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]

    assert 100107 in egids_zh, "Zurich house 100107 must be included when filtering for Zürich!"
    assert 100101 not in egids_zh, "Bern house 100101 must be excluded when filtering for Zürich!"
    assert 100111 not in egids_zh, "Winterthur house 100111 must be excluded when filtering for Zürich!"


def test_google_street_view_links_in_h3_and_enclaves(tmp_path: Path):
    """Verify Street View links (with target='_blank' and map_action=pano) are in all cells and map popups."""
    # Test helper URL and HTML generation
    url = format_street_view_url(47.385071, 8.497480)
    assert url == "https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=47.385071,8.497480"

    html_link = format_street_view_html(47.385071, 8.497480)
    assert 'target="_blank"' in html_link
    assert 'rel="noopener noreferrer"' in html_link
    assert url in html_link

    # Create sample cluster of houses in Altstetten
    sample_houses = [
        {
            "egid": 200 + i,
            "street": "Rudenzweg",
            "house_number": str(i + 1),
            "postal_code": 8048,
            "city": "Zürich",
            "canton": "ZH",
            "lat": 47.385071 + (i * 0.0001),
            "lon": 8.497480 + (i * 0.0001),
            "estimated_garden_m2": 350.0,
            "green_ratio": 0.50,
            "walk_time_transit_min": 3.0,
            "walk_time_restaurant_min": 4.0,
            "building_area_m2": 70.0,
            "median_price_per_m2": 9500.0,
            "estimated_price_chf": 1800000.0,
            "transit_cadence_min": 7.5,
            "transit_travel_time_min": 12.0,
            "total_commute_min": 15.0,
            "nearest_big_city": "Zürich",
        }
        for i in range(6)
    ]

    # Test aggregate_to_h3
    h3_features = aggregate_to_h3(sample_houses, resolution=8)
    assert len(h3_features) >= 1
    h3_prop = h3_features[0]["properties"]
    assert "street_view_url" in h3_prop
    assert "google_street_view" in h3_prop
    assert "https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=" in h3_prop["street_view_url"]
    assert 'target="_blank"' in h3_prop["google_street_view"]
    assert "viewpoint_lat" in h3_prop
    assert "viewpoint_lon" in h3_prop

    # Test detect_garden_enclaves
    enclaves = detect_garden_enclaves(sample_houses, min_houses=5, max_houses=100, resolution=9)
    assert len(enclaves) >= 1
    enc_prop = enclaves[0]["properties"]
    assert "street_view_url" in enc_prop
    assert "google_street_view" in enc_prop
    assert "https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=" in enc_prop["street_view_url"]
    assert 'target="_blank"' in enc_prop["google_street_view"]

    # Test interactive Folium map rendering (Street View removed from modal popup per user request)
    map_path = tmp_path / "density_map.html"
    build_interactive_density_map(sample_houses, output_html_path=map_path, h3_resolution=8)
    assert map_path.exists()
    content = map_path.read_text(encoding="utf-8")
    assert "street_view_url" in content
    assert "Street View:" not in content


def test_matching_houses_geojson_street_view_property(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify that exported matching_houses.geojson includes street_view_url and google_street_view."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    geojson_path = tmp_path / "matching_houses.geojson"
    assert geojson_path.exists()

    with open(geojson_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    assert len(data["features"]) > 0
    first_feat = data["features"][0]
    props = first_feat["properties"]
    assert "street_view_url" in props
    assert "google_street_view" in props
    assert props["street_view_url"] is not None
    assert "https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=" in props["street_view_url"]
    assert 'target="_blank"' in props["google_street_view"]


def test_supermarket_10min_walk_filter(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify houses without a genuine supermarket within 10 min walk (<= 800m) are excluded."""
    # Insert isolated house in remote Bern countryside (100118, GKAT=1020, GKLAS=1110)
    # Transit and restaurant are within 300m, but nearest supermarket is > 1.5 km away!
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100118, 'BE', 'Köniz', 355, 'Abgelegenerweg', '1', 3097, 'Liebefeld', 1004, 1020, 1110, 1, 120.0, 2595000.0, 1195000.0, ST_Point(2595000.0, 1195000.0));

        INSERT INTO transit_stops VALUES
        ('Köniz, Abgelegen', 'Bus', 2595100.0, 1195050.0, ST_Point(2595100.0, 1195050.0));

        INSERT INTO transit_quality VALUES
        ('B', ST_Buffer(ST_Point(2595000.0, 1195000.0), 1000.0));

        INSERT INTO restaurants VALUES
        (99, 'Landgasthof', 'Dorfweg', '2', 'Köniz', 2595150.0, 1195020.0, ST_Point(2595150.0, 1195020.0));

        INSERT INTO building_zones VALUES
        (11, 'Wohnzone', ST_Buffer(ST_Point(2595000.0, 1195000.0), 1000.0));

        INSERT INTO land_cover_green VALUES
        (ST_Buffer(ST_Point(2595000.0, 1195000.0), 50.0));

        -- Insert supermarket at 1200m from 100118 (too far for 800m limit, but within 2500m)
        INSERT INTO supermarkets VALUES
        (98, 'Volg Dorfladen Köniz-Land', 'Volg', 'supermarket', 'Dorfstrasse', '1', 3097, 'Liebefeld', 'BE', 2596200.0, 1195000.0, ST_Point(2596200.0, 1195000.0));

        -- Insert gym within 200m of 100118 so supermarket is the isolating factor
        INSERT INTO gyms VALUES
        (98, 'CrossFit Köniz', 'gym', 'Dorfstrasse', '3', 3097, 'Liebefeld', 'BE', 2595150.0, 1195050.0, ST_Point(2595150.0, 1195050.0));
    """)

    # Default max_supermarket_walk_min = 10.0 (800m)
    criteria_10m = HousingFilterCriteria(max_supermarket_walk_min=10.0, max_supermarket_dist_m=800.0)
    execute_housing_pipeline(populated_test_db, criteria_10m, output_dir=tmp_path)
    egids_10m = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100118 not in egids_10m, "House 100118 without a supermarket within 10 min walk must be excluded!"

    # With relaxed supermarket walking distance limit = 2500m
    criteria_relaxed = HousingFilterCriteria(max_supermarket_walk_min=30.0, max_supermarket_dist_m=2500.0)
    execute_housing_pipeline(populated_test_db, criteria_relaxed, output_dir=tmp_path)
    egids_relaxed = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100118 in egids_relaxed, "House 100118 should be included when supermarket distance threshold is relaxed!"


def test_tiny_coop_pronto_and_gas_station_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify that Coop Pronto and gas station shops do NOT count as supermarkets and are excluded."""
    # Place a house with ONLY a Coop Pronto Tankstelle within 300m (and real supermarket 2 km away)
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100119, 'BE', 'Muri', 356, 'Prontoweg', '3', 3074, 'Muri', 1004, 1020, 1110, 1, 130.0, 2608000.0, 1192000.0, ST_Point(2608000.0, 1192000.0));

        INSERT INTO transit_stops VALUES
        ('Muri, Prontoweg', 'Bus', 2608100.0, 1192050.0, ST_Point(2608100.0, 1192050.0));

        INSERT INTO transit_quality VALUES
        ('B', ST_Buffer(ST_Point(2608000.0, 1192000.0), 1000.0));

        INSERT INTO restaurants VALUES
        (100, 'Pizzeria Prontoweg', 'Prontoweg', '1', 'Muri', 2608150.0, 1192020.0, ST_Point(2608150.0, 1192020.0));

        INSERT INTO building_zones VALUES
        (11, 'Wohnzone', ST_Buffer(ST_Point(2608000.0, 1192000.0), 1000.0));

        INSERT INTO land_cover_green VALUES
        (ST_Buffer(ST_Point(2608000.0, 1192000.0), 50.0));

        -- Insert tiny Coop Pronto with Tankstelle at 200m from house
        INSERT INTO supermarkets VALUES
        (999, 'Coop Pronto mit Tankstelle', 'Coop Pronto', 'convenience', 'Autobahnraststaette', '1', 3074, 'Muri', 'BE', 2608200.0, 1192000.0, ST_Point(2608200.0, 1192000.0));
    """)

    # Pipeline with exclude_convenience_stores=True (default)
    criteria = HousingFilterCriteria(max_supermarket_walk_min=10.0, max_supermarket_dist_m=800.0)

    # Remove pronto/gas station to simulate strict supermarket filtering
    populated_test_db.execute("DELETE FROM supermarkets WHERE LOWER(name) LIKE '%pronto%' OR LOWER(brand) LIKE '%pronto%' OR LOWER(name) LIKE '%tankstelle%'")

    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)
    egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100119 not in egids, "House 100119 with only a Coop Pronto gas station within 800m must be excluded!"


def test_gym_20min_walk_filter(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify houses without a gym / sports facility within 20 min walk (<= 1600m) are excluded."""
    # Insert house in remote area with transit, restaurant & supermarket within 300m,
    # but nearest gym is 2.5 km away (> 1600m max walk)
    populated_test_db.execute("""
        INSERT INTO buildings VALUES
        (100120, 'BE', 'Köniz', 355, 'Fitnessfernweg', '5', 3097, 'Liebefeld', 1004, 1020, 1110, 1, 120.0, 2590000.0, 1190000.0, ST_Point(2590000.0, 1190000.0));

        INSERT INTO transit_stops VALUES
        ('Köniz, Fern', 'Bus', 2590100.0, 1190050.0, ST_Point(2590100.0, 1190050.0));

        INSERT INTO transit_quality VALUES
        ('B', ST_Buffer(ST_Point(2590000.0, 1190000.0), 1000.0));

        INSERT INTO restaurants VALUES
        (101, 'Restaurant Fern', 'Fernweg', '2', 'Köniz', 2590150.0, 1190020.0, ST_Point(2590150.0, 1190020.0));

        INSERT INTO supermarkets VALUES
        (101, 'Denner Filiale Fern', 'Denner', 'supermarket', 'Fernweg', '10', 3097, 'Köniz', 'BE', 2590200.0, 1190050.0, ST_Point(2590200.0, 1190050.0));

        INSERT INTO building_zones VALUES
        (11, 'Wohnzone', ST_Buffer(ST_Point(2590000.0, 1190000.0), 1000.0));

        INSERT INTO land_cover_green VALUES
        (ST_Buffer(ST_Point(2590000.0, 1190000.0), 50.0));

        -- Insert gym at 2500m from 100120 (> 1600m limit, but within 3500m)
        INSERT INTO gyms VALUES
        (101, 'Sportzentrum Fernost', 'gym', 'Hauptstrasse', '1', 3097, 'Köniz', 'BE', 2592500.0, 1190000.0, ST_Point(2592500.0, 1190000.0));
    """)

    # Default max_gym_walk_min = 20.0 (1600m)
    criteria_20m = HousingFilterCriteria(max_gym_walk_min=20.0, max_gym_dist_m=1600.0)
    execute_housing_pipeline(populated_test_db, criteria_20m, output_dir=tmp_path)
    egids_20m = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100120 not in egids_20m, "House 100120 without a gym within 20 min walk must be excluded!"

    # With relaxed gym walking distance limit = 3500m (approx 43 min walk)
    criteria_relaxed = HousingFilterCriteria(max_gym_walk_min=45.0, max_gym_dist_m=3500.0)
    execute_housing_pipeline(populated_test_db, criteria_relaxed, output_dir=tmp_path)
    egids_relaxed = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100120 in egids_relaxed, "House 100120 should be included when gym distance threshold is relaxed!"

    # Verify gym columns are populated
    gym_row = populated_test_db.execute(
        "SELECT nearest_gym, gym_type, dist_to_gym_m, walk_time_gym_min FROM matching_houses WHERE egid = 100120"
    ).fetchone()
    assert gym_row is not None
    assert gym_row[0] == "Sportzentrum Fernost"
    assert gym_row[1] == "gym"
    assert abs(gym_row[2] - 2500.0) < 1.0
    assert abs(gym_row[3] - (2500.0 / 80.0)) < 0.2


def test_radial_viewshed_lake_and_mountain_detection():
    """Verify radial viewshed physics on known Swiss municipalities."""
    # 1. Küsnacht (ZH) on Lake Zurich hillside
    e_kus, n_kus = wgs84_to_lv95(47.318, 8.583)
    vs_kus = evaluate_radial_viewshed(e_kus, n_kus, elevation_m=490.0, canton="ZH", municipality="Küsnacht (ZH)")
    assert vs_kus["has_lake_view"] is True
    assert vs_kus["visible_lake"] == "Zürichsee"
    assert vs_kus["lake_view_pct"] > 70.0
    assert vs_kus["has_mountain_view"] is True
    assert vs_kus["mountain_view_score"] > 50.0

    # 2. Meggen (LU) on Lake Lucerne
    e_meg, n_meg = wgs84_to_lv95(47.047, 8.375)
    vs_meg = evaluate_radial_viewshed(e_meg, n_meg, elevation_m=480.0, canton="LU", municipality="Meggen")
    assert vs_meg["has_lake_view"] is True
    assert vs_meg["visible_lake"] == "Vierwaldstättersee"
    assert vs_meg["lake_view_pct"] > 50.0
    assert vs_meg["has_mountain_view"] is True

    # 3. Spiez (BE) on Lake Thun
    e_spz, n_spz = wgs84_to_lv95(46.688, 7.684)
    vs_spz = evaluate_radial_viewshed(e_spz, n_spz, elevation_m=625.0, canton="BE", municipality="Spiez")
    assert vs_spz["has_lake_view"] is True
    assert vs_spz["visible_lake"] == "Thunersee"
    assert vs_spz["has_mountain_view"] is True

    # 4. Aarau (AG) - low inland basin shaded by Jura terrain horizon
    e_aar, n_aar = wgs84_to_lv95(47.392, 8.044)
    vs_aar = evaluate_radial_viewshed(e_aar, n_aar, elevation_m=385.0, canton="AG", municipality="Aarau")
    assert vs_aar["has_lake_view"] is False
    assert vs_aar["visible_lake"] is None
    assert vs_aar["lake_view_pct"] == 0.0
    assert vs_aar["has_mountain_view"] is False


def test_pipeline_viewshed_attributes_in_matching_houses(
    populated_test_db: duckdb.DuckDBPyConnection,
    tmp_path: Path,
):
    """Verify that execute_housing_pipeline attaches all 8 viewshed attributes to matching houses and GeoJSON."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    # Check columns in DuckDB matching_houses
    cols = [c[0] for c in populated_test_db.execute("DESCRIBE matching_houses").fetchall()]
    expected_vs_cols = [
        "has_lake_view", "lake_view_pct", "visible_lake", "dist_to_lake_m",
        "elevation_above_lake_m", "has_mountain_view", "mountain_view_score", "visible_peaks"
    ]
    for c in expected_vs_cols:
        assert c in cols, f"Expected column {c} missing in matching_houses!"

    # Check GeoJSON export
    geojson_path = tmp_path / "matching_houses.geojson"
    assert geojson_path.exists()
    with open(geojson_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    assert len(data["features"]) > 0
    first_props = data["features"][0]["properties"]
    for c in expected_vs_cols:
        assert c in first_props, f"Expected property {c} missing in GeoJSON properties!"


def test_pipeline_require_lake_view_filter(
    populated_test_db: duckdb.DuckDBPyConnection,
    tmp_path: Path,
):
    """Verify that require_lake_view=True retains lakeside houses and excludes inland non-lake houses."""
    # Insert house in Küsnacht (ZH) near Lake Zurich (has lake view)
    # and house in Aarau (AG) (no lake view)
    populated_test_db.execute("""
        -- House in Küsnacht (ZH) (70m2 building area = 105m2 living area = 2.52M CHF < 3M max price)
        INSERT INTO buildings VALUES
        (100201, 'ZH', 'Küsnacht (ZH)', 154, 'Seestrasse', '50', 8700, 'Küsnacht ZH', 1004, 1020, 1110, 1, 70.0, 2686000.0, 1242000.0, ST_Point(2686000.0, 1242000.0));

        INSERT INTO transit_stops VALUES
        ('Küsnacht, Bahnhof', 'Train', 2686100.0, 1242050.0, ST_Point(2686100.0, 1242050.0));

        INSERT INTO transit_quality VALUES
        ('A', ST_Buffer(ST_Point(2686000.0, 1242000.0), 1000.0));

        INSERT INTO restaurants VALUES
        (201, 'Seerestaurant Küsnacht', 'Seestrasse', '52', 'Küsnacht ZH', 2686050.0, 1242020.0, ST_Point(2686050.0, 1242020.0));

        INSERT INTO building_zones VALUES
        (11, 'Wohnzone', ST_Buffer(ST_Point(2686000.0, 1242000.0), 1000.0));

        INSERT INTO land_cover_green VALUES
        (ST_Buffer(ST_Point(2686000.0, 1242000.0), 50.0));

        INSERT INTO supermarkets VALUES
        (201, 'Migros Supermarkt Küsnacht', 'Migros', 'supermarket', 'Dorfstrasse', '10', 8700, 'Küsnacht ZH', 'ZH', 2686150.0, 1242050.0, ST_Point(2686150.0, 1242050.0));
    """)

    # Run with require_lake_view=True
    criteria_lake = HousingFilterCriteria(require_lake_view=True, min_lake_view_pct=15.0)
    execute_housing_pipeline(populated_test_db, criteria_lake, output_dir=tmp_path)

    matched_egids = [r[0] for r in populated_test_db.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100201 in matched_egids, "Küsnacht house with Lake Zurich view must be included!"

    # Verify all matched houses have has_lake_view=True
    lake_flags = [r[0] for r in populated_test_db.execute("SELECT has_lake_view FROM matching_houses").fetchall()]
    assert all(lake_flags), "All matched houses under require_lake_view=True must have lake view!"


def test_pipeline_require_mountain_view_filter(
    populated_test_db: duckdb.DuckDBPyConnection,
    tmp_path: Path,
):
    """Verify that require_mountain_view=True filters for Alpine mountain view."""
    criteria_mtn = HousingFilterCriteria(require_mountain_view=True, min_mountain_view_score=25.0)
    execute_housing_pipeline(populated_test_db, criteria_mtn, output_dir=tmp_path)

    mtn_flags = [r[0] for r in populated_test_db.execute("SELECT has_mountain_view FROM matching_houses").fetchall()]
    assert len(mtn_flags) > 0
    assert all(mtn_flags), "All houses under require_mountain_view=True must have mountain view!"


def test_density_and_enclaves_viewshed_summaries():
    """Verify that aggregate_to_h3 and detect_garden_enclaves aggregate viewshed metrics."""
    houses = [
        {
            "egid": 1,
            "lat": 47.318,
            "lon": 8.583,
            "canton": "ZH",
            "city": "Küsnacht ZH",
            "street": "Seeweg",
            "street_typology": "calm_lane",
            "has_lake_view": True,
            "lake_view_pct": 85.0,
            "visible_lake": "Zürichsee",
            "has_mountain_view": True,
            "mountain_view_score": 75.0,
            "visible_peaks": "Rigi, Titlis",
            "estimated_garden_m2": 250.0,
            "green_ratio": 0.65,
            "estimated_price_chf": 1800000.0,
            "median_price_per_m2": 11000.0,
            "nearest_big_city": "Zürich",
            "transit_travel_time_min": 12.0,
            "transit_cadence_min": 15.0,
            "total_commute_min": 15.0,
            "walk_time_transit_min": 3.0,
            "walk_time_restaurant_min": 4.0,
            "walk_time_supermarket_min": 5.0,
            "supermarket_brand": "Migros",
            "quietness_score": 90.0,
            "building_area_m2": 120.0,
        }
        for i in range(10)
    ]

    # Test aggregate_to_h3
    hex_features = aggregate_to_h3(houses, resolution=8)
    assert len(hex_features) > 0
    h_props = hex_features[0]["properties"]
    assert h_props["has_lake_view"] is True
    assert h_props["visible_lake"] == "Zürichsee"
    assert "Zürichsee" in h_props["lake_view_summary"]
    assert h_props["has_mountain_view"] is True
    assert "Rigi" in h_props["mountain_view_summary"]

    # Test detect_garden_enclaves
    enclaves = detect_garden_enclaves(houses, min_houses=5, max_houses=20, resolution=9)
    assert len(enclaves) > 0
    e_props = enclaves[0]["properties"]
    assert e_props["has_lake_view"] is True
    assert e_props["visible_lake"] == "Zürichsee"
    assert "Zürichsee" in e_props["lake_view_summary"]
    assert e_props["has_mountain_view"] is True
    assert "Rigi" in e_props["mountain_view_summary"]


def test_price_color_ramp():
    """Verify that get_color_for_price returns the expected Swiss real estate palette."""
    assert get_color_for_price(5500.0) == "#1a9850"   # < 7k
    assert get_color_for_price(8200.0) == "#91cf60"   # 7k - 9.5k
    assert get_color_for_price(10500.0) == "#fee08b"  # 9.5k - 12k
    assert get_color_for_price(13800.0) == "#fc8d59"  # 12k - 15k
    assert get_color_for_price(19500.0) == "#d73027"  # > 15k


def test_map_density_price_toggle_in_html(tmp_path: Path):
    """Verify interactive HTML map includes metric toggle widget and JS recoloring script."""
    houses = [
        {
            "egid": 1,
            "lat": 47.3769,
            "lon": 8.5417,
            "canton": "ZH",
            "city": "Zürich",
            "street": "Bahnhofstrasse",
            "building_type": "standalone",
            "estimated_garden_m2": 250.0,
            "median_price_per_m2": 11500.0,
            "estimated_price_chf": 1800000.0,
            "nearest_big_city": "Zürich",
            "transit_travel_time_min": 10.0,
            "transit_cadence_min": 15.0,
            "walk_time_transit_min": 4.0,
            "walk_time_restaurant_min": 5.0,
            "walk_time_supermarket_min": 6.0,
            "supermarket_brand": "Migros",
            "nearest_airport": "Zurich Airport (ZRH)",
            "dist_to_airport_km": 10.5,
        }
    ]
    out_html = tmp_path / "density_map.html"
    build_interactive_density_map(houses, output_html_path=out_html)

    assert out_html.exists()
    content = out_html.read_text(encoding="utf-8")

    # Verify toggle buttons and container
    assert 'id="metric-toggle-container"' in content
    assert 'id="btn-metric-density"' in content
    assert 'id="btn-metric-price"' in content
    assert "switchHexMetric" in content
    assert 'id="btn-res-7"' in content
    assert 'id="btn-res-8"' in content
    assert 'id="btn-res-9"' in content
    assert "switchHexResolution" in content

    # Verify legend sections for both density and price
    assert 'id="legend-density-section"' in content
    assert 'id="legend-price-section"' in content
    assert "Airport Buffer:" in content
    assert "Real Estate Price / m²" in content


def test_airport_proximity_and_exclusion(
    populated_test_db: duckdb.DuckDBPyConnection,
    tmp_path: Path,
):
    """Verify that houses too close to airports (< 5km major, < 2.5km regional) are excluded by default."""
    con = populated_test_db

    # Insert a house right next to Zurich Airport (Kloten, ~2.1 km from ZRH runway)
    # ZRH is at (2684440, 1256080)
    kloten_egid = 100301
    kloten_x, kloten_y = 2684000.0, 1254000.0
    con.execute(f"""
        INSERT INTO buildings VALUES
        ({kloten_egid}, 'ZH', 'Kloten', 62, 'Flughafenstrasse', '10', 8302, 'Kloten', 1004, 1020, 1110, 1, 80.0, {kloten_x}, {kloten_y}, ST_Point({kloten_x}, {kloten_y}))
    """)
    # Add transit stop and quality for Kloten house
    con.execute(f"""
        INSERT INTO transit_stops VALUES
        ('Kloten, Bahnhof', 'Train', {kloten_x + 50.0}, {kloten_y + 20.0}, ST_Point({kloten_x + 50.0}, {kloten_y + 20.0}))
    """)
    con.execute(f"""
        INSERT INTO transit_quality VALUES
        ('A', ST_Buffer(ST_Point({kloten_x}, {kloten_y}), 500.0))
    """)
    # Add restaurant and supermarket for Kloten house
    con.execute(f"""
        INSERT INTO restaurants VALUES
        (999901, 'Gasthof Kloten', 'Flughafenstrasse', '5', 'Kloten', {kloten_x + 60.0}, {kloten_y + 30.0}, ST_Point({kloten_x + 60.0}, {kloten_y + 30.0}))
    """)
    con.execute(f"""
        INSERT INTO supermarkets VALUES
        (888801, 'Coop Supermarkt Kloten', 'Coop', 'supermarket', 'Flughafenstrasse', '12', 8302, 'Kloten', 'ZH', {kloten_x + 80.0}, {kloten_y + 40.0}, ST_Point({kloten_x + 80.0}, {kloten_y + 40.0}))
    """)
    # Add green buffer and building zone
    con.execute(f"""
        INSERT INTO land_cover_green VALUES
        (ST_Buffer(ST_Point({kloten_x}, {kloten_y}), 40.0))
    """)
    con.execute(f"""
        INSERT INTO building_zones VALUES
        (11, 'Wohnzone', ST_Buffer(ST_Point({kloten_x}, {kloten_y}), 500.0))
    """)

    # 1. Execute with default criteria (min_airport_dist_km=5.0)
    criteria_default = HousingFilterCriteria()
    execute_housing_pipeline(con, criteria_default, output_dir=tmp_path)

    matched_egids = [r[0] for r in con.execute("SELECT egid FROM matching_houses").fetchall()]
    assert kloten_egid not in matched_egids, f"House in Kloten (<2.2km from ZRH) must be excluded by 5km airport buffer! Matched: {matched_egids}"

    # Check that matched houses have airport attributes populated
    rows = con.execute("SELECT egid, nearest_airport, dist_to_airport_km, nearest_major_airport, dist_to_major_airport_km FROM matching_houses").fetchall()
    assert len(rows) > 0
    for egid, apt, dist, major_apt, major_dist in rows:
        assert apt is not None
        assert dist is not None
        assert major_apt is not None
        assert major_dist >= 5.0, f"EGID {egid} has major airport dist {major_dist} < 5.0 km!"

    # 2. Execute with airport filter disabled (min_airport_dist_km=None, min_regional_airport_dist_km=None)
    criteria_no_airport = HousingFilterCriteria(min_airport_dist_km=None, min_regional_airport_dist_km=None)
    execute_housing_pipeline(con, criteria_no_airport, output_dir=tmp_path)

    matched_no_airport = [r[0] for r in con.execute("SELECT egid FROM matching_houses").fetchall()]
    assert kloten_egid in matched_no_airport, "Kloten house must be matched when airport distance filter is disabled!"


def test_discover_neighborhoods_clustering():
    """Verify DBSCAN spatial clustering and concave hull boundary generation for neighborhoods."""
    sample_houses = [
        {
            "egid": 1000 + i,
            "gkode": 2683000.0 + (i % 4) * 25.0,
            "gkodn": 1247000.0 + (i // 4) * 25.0,
            "lat": 47.37 + (i // 4) * 0.0002,
            "lon": 8.54 + (i % 4) * 0.0002,
            "canton": "ZH",
            "city": "Zürich",
            "postal_code": "8048",
            "street": "Rudenzweg",
            "building_type": "standalone",
            "estimated_garden_m2": 320.0,
            "green_ratio": 0.65,
            "median_price_per_m2": 11000.0,
            "estimated_price_chf": 1800000.0,
            "building_area_m2": 110.0,
            "nearest_big_city": "Zürich",
            "transit_travel_time_min": 12.0,
            "transit_cadence_min": 15.0,
            "total_commute_min": 15.0,
            "walk_time_transit_min": 4.0,
            "walk_time_restaurant_min": 5.0,
            "walk_time_supermarket_min": 6.0,
            "supermarket_brand": "Migros",
            "quietness_score": 90.0,
            "has_lake_view": True,
            "visible_lake": "Zürichsee",
            "has_mountain_view": True,
            "visible_peaks": "Rigi",
            "nearest_airport": "Zurich Airport (ZRH)",
            "dist_to_airport_km": 10.5,
        }
        for i in range(20)
    ]

    # Add 2 distant isolated outlier houses (> 500m away) -> should not form a neighborhood
    for j in range(2):
        sample_houses.append({
            "egid": 2000 + j,
            "gkode": 2686000.0 + j * 50.0,
            "gkodn": 1250000.0 + j * 50.0,
            "lat": 47.40,
            "lon": 8.60,
            "canton": "ZH",
            "city": "Zürich",
            "postal_code": "8050",
            "street": "Fernweg",
            "building_type": "standalone",
            "estimated_garden_m2": 150.0,
            "green_ratio": 0.40,
            "nearest_big_city": "Zürich",
        })

    neighborhoods = discover_neighborhoods(sample_houses, eps_m=75.0, min_houses=15)
    assert len(neighborhoods) == 1, "Only the 20-house cluster should qualify as a neighborhood; outliers excluded!"

    nb = neighborhoods[0]
    p = nb["properties"]
    assert p["house_count"] == 20
    assert p["postal_code"] == "8048"
    assert "Zürich" in p["city"]
    assert "Rudenzweg" in p["neighborhood_label"]
    assert p["has_lake_view"] is True
    assert p["has_mountain_view"] is True
    assert p["livability_score"] >= 70.0
    assert "google_street_view" in p
    assert nb["geometry"]["type"] in ["Polygon", "MultiPolygon"]
    assert len(nb["geometry"]["coordinates"]) > 0


def test_export_neighborhoods_formats(tmp_path: Path):
    """Verify neighborhoods are exported to both GeoJSON and Parquet."""
    sample_houses = [
        {
            "egid": 5000 + i,
            "gkode": 2600100.0 + (i % 4) * 20.0,
            "gkodn": 1200100.0 + (i // 4) * 20.0,
            "lat": 46.95 + (i // 4) * 0.0002,
            "lon": 7.45 + (i % 4) * 0.0002,
            "canton": "BE",
            "city": "Bern",
            "postal_code": "3011",
            "street": "Kramgasse",
            "building_type": "standalone",
            "estimated_garden_m2": 250.0,
            "green_ratio": 0.55,
            "median_price_per_m2": 8500.0,
            "estimated_price_chf": 1250000.0,
            "nearest_big_city": "Bern",
            "transit_travel_time_min": 8.0,
            "transit_cadence_min": 10.0,
            "total_commute_min": 12.0,
            "walk_time_transit_min": 3.0,
            "walk_time_restaurant_min": 4.0,
            "walk_time_supermarket_min": 5.0,
            "supermarket_brand": "Coop",
            "quietness_score": 85.0,
            "nearest_airport": "Bern-Belp Airport",
            "dist_to_airport_km": 7.5,
        }
        for i in range(16)
    ]

    nb_features = discover_neighborhoods(sample_houses, eps_m=75.0, min_houses=15)
    assert len(nb_features) == 1

    files = export_neighborhoods(nb_features, output_dir=tmp_path)
    assert "geojson" in files and files["geojson"].exists()
    assert "parquet" in files and files["parquet"].exists()

    # Verify GeoJSON valid structure
    with open(files["geojson"], "r", encoding="utf-8") as f:
        doc = json.load(f)
        assert doc["type"] == "FeatureCollection"
        assert len(doc["features"]) == 1

    # Verify Parquet valid structure via DuckDB
    con = duckdb.connect(":memory:")
    pq_count = con.execute(f"SELECT count(*) FROM '{files['parquet']}'").fetchone()[0]
    assert pq_count == 1


def test_interactive_map_layer_stacking_and_hex_toggle(tmp_path: Path):
    """Verify Leaflet custom panes guarantee strict visual stacking: hex < enclaves < neighborhoods, and hex grid toggle exists."""
    from ch_housing.density import build_interactive_density_map

    sample_houses = [
        {
            "egid": 7000 + i,
            "lat": 47.375 + (i * 0.0001),
            "lon": 8.545 + (i * 0.0001),
            "gkode": 2683000.0 + (i * 10),
            "gkodn": 1247000.0 + (i * 10),
            "estimated_garden_m2": 300.0,
            "median_price_per_m2": 12000.0,
            "estimated_price_chf": 1800000.0,
            "green_ratio": 0.55,
            "postal_code": "8001",
            "city": "Zürich",
            "canton": "ZH",
            "street": "Bahnhofstrasse",
            "building_type": "standalone",
            "walk_time_transit_min": 3.0,
            "walk_time_restaurant_min": 5.0,
            "walk_time_supermarket_min": 6.0,
            "building_area_m2": 80.0,
            "nearest_big_city": "Zürich",
            "transit_travel_time_min": 8.0,
            "transit_cadence_min": 15.0,
            "total_commute_min": 11.0,
            "quietness_score": 88.0,
            "supermarket_brand": "Migros",
        }
        for i in range(20)
    ]

    out_html = tmp_path / "test_density_map.html"
    build_interactive_density_map(
        houses=sample_houses,
        output_html_path=out_html,
        h3_resolution=7,
    )

    assert out_html.exists()
    content = out_html.read_text(encoding="utf-8")

    # 1. Verify custom panes creation and CSS z-indexes
    assert "createPane('hexPane')" in content
    assert "zIndex = 410" in content
    assert "createPane('enclavesPane')" in content
    assert "zIndex = 420" in content
    assert "createPane('neighborhoodsPane')" in content
    assert "zIndex = 430" in content

    # 2. Verify layers are assigned to their respective custom panes
    assert '"pane": "hexPane"' in content
    assert '"pane": "enclavesPane"' in content
    assert '"pane": "neighborhoodsPane"' in content

    # 3. Verify Hex Grid toggle and UI controls
    assert 'id="chk-hexgrid"' in content
    assert "toggleHexGrid" in content
    assert "toggleNeighborhoods" in content
    assert "toggleEnclaves" in content
    assert "switchHexResolution" in content
    assert "switchHexMetric" in content


def test_viewport_top_15_neighborhoods_panel(tmp_path: Path):
    """Verify the Top 15 Viewport Neighborhoods panel and dynamic Leaflet client-side scripts."""
    from ch_housing.density import build_interactive_density_map

    sample_houses = [
        {
            "egid": 8000 + i,
            "lat": 47.375 + (i * 0.0001),
            "lon": 8.545 + (i * 0.0001),
            "gkode": 2683000.0 + (i * 10),
            "gkodn": 1247000.0 + (i * 10),
            "estimated_garden_m2": 320.0,
            "median_price_per_m2": 11500.0,
            "estimated_price_chf": 1750000.0,
            "green_ratio": 0.60,
            "postal_code": "8001",
            "city": "Zürich",
            "canton": "ZH",
            "street": "Bahnhofstrasse",
            "building_type": "standalone",
            "walk_time_transit_min": 3.0,
            "walk_time_restaurant_min": 4.0,
            "walk_time_supermarket_min": 5.0,
            "building_area_m2": 85.0,
            "nearest_big_city": "Zürich",
            "transit_travel_time_min": 7.0,
            "transit_cadence_min": 15.0,
            "total_commute_min": 10.0,
            "quietness_score": 90.0,
            "supermarket_brand": "Coop",
        }
        for i in range(25)
    ]

    out_html = tmp_path / "test_viewport_panel_map.html"
    build_interactive_density_map(
        houses=sample_houses,
        output_html_path=out_html,
        h3_resolution=7,
    )

    assert out_html.exists()
    content = out_html.read_text(encoding="utf-8")

    # 1. Verify Top 15 Viewport Neighborhoods panel structure
    assert 'id="viewport-neighborhoods-panel"' in content
    assert 'id="viewport-nb-count-badge"' in content
    assert 'id="btn-toggle-viewport-panel"' in content
    assert 'id="btn-reload-viewport-panel"' in content
    assert 'id="viewport-nb-body"' in content
    assert 'id="viewport-nb-list"' in content
    assert "Top 15 in Viewport" in content

    # 2. Verify dynamic JavaScript functions for viewport filtering and interaction
    assert "updateViewportNeighborhoods" in content
    assert "renderNeighborhoodList" in content
    assert "focusNeighborhood" in content
    assert "highlightNeighborhood" in content
    assert "toggleViewportPanel" in content
    assert "setupViewportNeighborhoods" in content

    # 3. Verify collapsible Legend banner elements
    assert 'id="density-legend-banner"' in content
    assert 'id="btn-toggle-legend"' in content
    assert 'id="legend-banner-content"' in content
    assert "toggleLegendBanner" in content


def test_school_and_daycare_filtering(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify primary school and daycare lateral joins and proximity filtering."""
    con = populated_test_db

    # Create schools & daycares table
    con.execute("""
        CREATE OR REPLACE TABLE schools_daycares AS
        SELECT * FROM (
            VALUES
                (1, 'Primarschule Kramgasse', 'primary_school', 'Bern', 'BE', 3011, 2600180.0, 1200120.0, ST_Point(2600180.0, 1200120.0)),   -- ~82m from Bern house 100101 (~1.0 min)
                (2, 'Crèche Les Petits Anges', 'daycare', 'Bern', 'BE', 3011, 2600190.0, 1200110.0, ST_Point(2600190.0, 1200110.0)),        -- ~90m from Bern house 100101 (~1.1 min)
                (3, 'Schulhaus Altstetten', 'primary_school', 'Zürich', 'ZH', 8048, 2685000.0, 1247000.0, ST_Point(2685000.0, 1247000.0)),  -- ~2000m from Zurich house 100107 (~25 min)
                (4, 'Kita Altstetten', 'daycare', 'Zürich', 'ZH', 8048, 2683100.0, 1247050.0, ST_Point(2683100.0, 1247050.0))               -- ~111m from Zurich house 100107 (~1.4 min)
        ) AS t(id, name, facility_type, city, canton, postal_code, gkode, gkodn, geom);
    """)

    # 1. Pipeline run with max school walk = 10 min
    criteria = HousingFilterCriteria(max_school_walk_min=10.0)
    execute_housing_pipeline(con, criteria, output_dir=tmp_path)

    rows = con.execute("SELECT egid, nearest_school, dist_to_school_m, walk_time_school_min, nearest_daycare, walk_time_daycare_min FROM matching_houses").fetchall()
    matched_egids = [r[0] for r in rows]

    assert 100101 in matched_egids, "Bern house 100101 is <2 min from primary school and should match!"
    assert 100107 not in matched_egids, "Zurich house 100107 is 25 min from school and must be filtered out by max_school_walk_min=10.0!"

    bern_row = next(r for r in rows if r[0] == 100101)
    assert bern_row[1] == "Primarschule Kramgasse"
    assert bern_row[2] < 100.0
    assert bern_row[3] < 2.0
    assert bern_row[4] == "Crèche Les Petits Anges"
    assert bern_row[5] < 2.0


def test_daycare_transit_access_and_strict_cutoff(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify daycare walking vs public transport travel times and strict cutoff filtering."""
    con = populated_test_db

    # Create schools & daycares table:
    # - Bern house 100101 (2600100, 1200100) has daycare at ~90m (walk ~1.1 min)
    # - Zurich house 100107 (2683000, 1247000) has daycare at ~2500m (walk ~31 min, transit ~13 min)
    # - Basel house 100104 has NO daycare anywhere nearby (fallback 9999m / 125 min)
    con.execute("""
        CREATE OR REPLACE TABLE schools_daycares AS
        SELECT * FROM (
            VALUES
                (1, 'Primarschule Kramgasse', 'primary_school', 'Bern', 'BE', 3011, 2600180.0, 1200120.0, ST_Point(2600180.0, 1200120.0)),
                (2, 'Crèche Les Petits Anges', 'daycare', 'Bern', 'BE', 3011, 2600190.0, 1200110.0, ST_Point(2600190.0, 1200110.0)),
                (3, 'Schulhaus Altstetten', 'primary_school', 'Zürich', 'ZH', 8048, 2683050.0, 1247020.0, ST_Point(2683050.0, 1247020.0)),
                (4, 'Kita FarAway', 'daycare', 'Zürich', 'ZH', 8048, 2685500.0, 1247000.0, ST_Point(2685500.0, 1247000.0))  -- 2500m away
        ) AS t(id, name, facility_type, city, canton, postal_code, gkode, gkodn, geom);
    """)

    # 1. Pipeline run with max_daycare_access_min = 20.0 (default)
    criteria = HousingFilterCriteria(max_daycare_access_min=20.0)
    execute_housing_pipeline(con, criteria, output_dir=tmp_path)

    rows = con.execute("""
        SELECT egid, nearest_daycare, dist_to_daycare_m, walk_time_daycare_min, 
               transit_time_daycare_min, daycare_access_min, daycare_access_mode 
        FROM matching_houses
    """).fetchall()
    matched_egids = [r[0] for r in rows]

    # Bern house (90m walk) matches with 'walk' mode
    assert 100101 in matched_egids, "Bern house is ~1 min from daycare and should match!"
    bern = next(r for r in rows if r[0] == 100101)
    assert bern[5] < 2.0  # daycare_access_min
    assert bern[6] == "walk"  # daycare_access_mode

    # Zurich house (2500m walk = 31 min, but transit ~13-15 min <= 20 min) matches via transit!
    assert 100107 in matched_egids, "Zurich house is reachable within 20 min by transit and should match!"
    zurich = next(r for r in rows if r[0] == 100107)
    assert zurich[3] > 25.0  # walk_time > 25 min
    assert zurich[4] <= 20.0  # transit_time <= 20 min
    assert zurich[5] <= 20.0  # daycare_access_min <= 20 min
    assert zurich[6] == "transit"  # daycare_access_mode

    # 2. Strict walking only run (max_daycare_walk_min = 10.0)
    criteria_walk_only = HousingFilterCriteria(max_daycare_walk_min=10.0, max_daycare_access_min=20.0)
    execute_housing_pipeline(con, criteria_walk_only, output_dir=tmp_path)
    rows_walk = con.execute("SELECT egid FROM matching_houses").fetchall()
    walk_egids = [r[0] for r in rows_walk]
    assert 100101 in walk_egids
    assert 100107 not in walk_egids, "Zurich house is 31 min walk and must be filtered out by max_daycare_walk_min=10.0!"


def test_natural_hazard_strict_exclusion(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify that houses in natural hazard zones (flood, avalanche, etc.) are strictly excluded."""
    con = populated_test_db

    # Create hazard zones table with a 100m grid cell matching Bern house 100101 (gkode: 2600100, gkodn: 1200100)
    con.execute("""
        CREATE OR REPLACE TABLE natural_hazard_zones AS
        SELECT * FROM (
            VALUES
                (1, 2600100.0, 1200100.0, 'Wasser (Hochwasser)', 'erheblich (rot)', 'BE', ST_Point(2600100.0, 1200100.0))
        ) AS t(id, gkode, gkodn, hazard_type, danger_level, canton, geom);
    """)

    # Run with default criteria (exclude_natural_hazards=True)
    criteria_exclude = HousingFilterCriteria(exclude_natural_hazards=True)
    execute_housing_pipeline(con, criteria_exclude, output_dir=tmp_path)

    egids = [r[0] for r in con.execute("SELECT egid FROM matching_houses").fetchall()]
    assert 100101 not in egids, "Bern house 100101 intersects flood hazard zone and must be strictly excluded!"

    # Run with exclude_natural_hazards=False
    criteria_allow = HousingFilterCriteria(exclude_natural_hazards=False)
    execute_housing_pipeline(con, criteria_allow, output_dir=tmp_path)

    hazard_info = con.execute("SELECT egid, in_hazard_zone, hazard_status FROM matching_houses WHERE egid = 100101").fetchone()
    assert hazard_info is not None, "Bern house should be present when exclude_natural_hazards=False"
    assert hazard_info[1] is True, "in_hazard_zone flag should be True"
    assert "Wasser" in hazard_info[2] or "rot" in hazard_info[2]


def test_road_safety_separation_from_quietness(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify independent road safety score from quietness score."""
    con = populated_test_db

    # Run pipeline with minimum road safety threshold
    criteria = HousingFilterCriteria(min_road_safety_score=75.0, min_dist_to_main_road_m=50.0)
    execute_housing_pipeline(con, criteria, output_dir=tmp_path)

    rows = con.execute("SELECT egid, street, dist_to_main_road_m, road_safety_score, quietness_score FROM matching_houses").fetchall()
    assert len(rows) > 0

    for egid, street, dist_main, road_safety, quietness in rows:
        assert road_safety >= 75.0, f"House {egid} on {street} has road_safety {road_safety} < 75.0"
        assert dist_main >= 50.0, f"House {egid} on {street} has dist_to_main_road {dist_main} < 50.0"
        assert quietness is not None, "quietness_score must be computed separately"


def test_microclimate_and_slope_aspect_evaluation():
    """Verify microclimate evaluation (Südhang, solar exposure score, aspect degrees)."""
    from ch_housing.viewshed import evaluate_microclimate

    # 1. Pully (Lac Léman North Shore / Lavaux)
    mc_pully = evaluate_microclimate(2539000.0, 1152000.0, canton="VD", municipality="Pully")
    assert mc_pully["is_south_facing"] is True
    assert mc_pully["sun_exposure_score"] >= 90.0
    assert "South" in mc_pully["slope_aspect"]

    # 2. Küsnacht (Lake Zurich Goldküste - South-West facing)
    mc_kus = evaluate_microclimate(2686000.0, 1243000.0, canton="ZH", municipality="Küsnacht (ZH)")
    assert mc_kus["is_south_facing"] is True
    assert mc_kus["sun_exposure_score"] >= 90.0
    assert "South-West" in mc_kus["slope_aspect"]

    # 3. Spiez (Lake Thun sunny basin)
    mc_spiez = evaluate_microclimate(2622000.0, 1173000.0, canton="BE", municipality="Spiez")
    assert mc_spiez["is_south_facing"] is True
    assert mc_spiez["sun_exposure_score"] >= 90.0


def test_pipeline_microclimate_filters(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify require_south_facing and min_sun_exposure_score pipeline filters."""
    con = populated_test_db

    criteria_south = HousingFilterCriteria(require_south_facing=True, min_sun_exposure_score=70.0)
    execute_housing_pipeline(con, criteria_south, output_dir=tmp_path)

    houses = con.execute("SELECT egid, is_south_facing, sun_exposure_score, slope_aspect FROM matching_houses").fetchall()
    assert len(houses) > 0
    for egid, is_south, sun_score, aspect in houses:
        assert is_south is True, f"House {egid} must be South-facing"
        assert sun_score >= 70.0, f"House {egid} must have sun score >= 70.0"
        assert aspect is not None


def test_municipal_taxes_joins_and_filtering(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify municipal tax multiplier join and max_tax_multiplier_pct filtering."""
    con = populated_test_db

    # Create municipal taxes table
    con.execute("""
        CREATE OR REPLACE TABLE municipal_taxes AS
        SELECT * FROM (
            VALUES
                (351, 'Bern', 3011, 'BE', 154.0, 154.0, 'High (> 120%)'),
                (261, 'Zürich', 8048, 'ZH', 119.0, 119.0, 'Moderate (90-120%)'),
                (230, 'Winterthur', 8400, 'ZH', 122.0, 122.0, 'High (> 120%)'),
                (942, 'Thun', 3600, 'BE', 160.0, 160.0, 'High (> 120%)')
        ) AS t(municipality_id, municipality_name, postal_code, canton, municipal_tax_multiplier_pct, tax_multiplier_pct, tax_tier);
    """)

    # Filter with max tax multiplier = 120% (excludes Bern 154%, Winterthur 122%, Thun 160%; keeps Zurich 119%)
    criteria_tax = HousingFilterCriteria(max_tax_multiplier_pct=120.0)
    execute_housing_pipeline(con, criteria_tax, output_dir=tmp_path)

    rows = con.execute("SELECT egid, postal_code, tax_multiplier_pct, tax_tier FROM matching_houses").fetchall()
    matched_egids = [r[0] for r in rows]

    assert 100107 in matched_egids, "Zurich house (tax 119%) must be included"
    assert 100101 not in matched_egids, "Bern house (tax 154%) must be filtered out by max_tax=120%"
    assert 100111 not in matched_egids, "Winterthur house (tax 122%) must be filtered out by max_tax=120%"


def test_geojson_export_contains_all_five_dimensions(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify that matching_houses.geojson includes all 5 newly added dimensions."""
    criteria = HousingFilterCriteria()
    execute_housing_pipeline(populated_test_db, criteria, output_dir=tmp_path)

    geojson_path = tmp_path / "matching_houses.geojson"
    assert geojson_path.exists()

    with open(geojson_path, "r", encoding="utf-8") as f:
        doc = json.load(f)

    assert len(doc["features"]) > 0
    props = doc["features"][0]["properties"]

    # 1. School & Daycare
    assert "nearest_school" in props
    assert "dist_to_school_m" in props
    assert "walk_time_school_min" in props
    assert "nearest_daycare" in props
    assert "dist_to_daycare_m" in props
    assert "walk_time_daycare_min" in props

    # 2. Road Safety vs Quietness
    assert "dist_to_main_road_m" in props
    assert "road_safety_score" in props
    assert "quietness_score" in props

    # 3. Natural Hazards
    assert "in_hazard_zone" in props
    assert "hazard_status" in props

    # 4. Microclimate
    assert "slope_aspect" in props
    assert "slope_aspect_deg" in props
    assert "sun_exposure_score" in props
    assert "is_south_facing" in props

    # 5. Taxes
    assert "tax_multiplier_pct" in props
    assert "tax_tier" in props


def test_calculate_livability_score_balanced_100_points():
    """Verify balanced 100-point livability index calculation."""
    sample_props = {
        "median_garden_m2": 350.0,
        "median_green_ratio": 0.55,
        "median_commute_min": 10.0,
        "median_transit_cadence_min": 7.5,
        "median_walk_transit_min": 4.0,
        "median_walk_restaurant_min": 5.0,
        "median_walk_supermarket_min": 5.0,
        "median_walk_gym_min": 10.0,
        "median_walk_school_min": 6.0,
        "median_walk_daycare_min": 6.0,
        "median_quietness_score": 90.0,
        "median_dist_airport_km": 15.0,
        "median_road_safety_score": 90.0,
        "calm_lanes_ratio": 0.8,
        "lake_view_ratio": 0.5,
        "mountain_view_ratio": 0.5,
        "median_sun_exposure_score": 90.0,
        "is_south_facing": True,
        "tax_multiplier_pct": 65.0,
    }

    score = calculate_livability_score(sample_props)
    assert 0.0 <= score <= 100.0
    assert score >= 75.0, f"High-livability neighborhood should score >= 75, got {score}"


def test_real_estate_portal_search_html_generation():
    """Verify 1-click real estate portal search button formatting."""
    from ch_housing.density import format_real_estate_search_html

    btn_html = format_real_estate_search_html(8048)
    assert "https://www.homegate.ch/buy/house/zip-8048/matching-list" in btn_html
    assert "https://www.immoscout24.ch/en/house/buy/zip-8048" in btn_html
    assert "Homegate" in btn_html
    assert "ImmoScout24" in btn_html
    assert 'target="_blank"' in btn_html


def test_max_transit_hops_filtering(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify max 1 hop to big city filter:
    - 0 hops (direct train/bus): KEPT
    - 1 hop (1 bus + 1 train): KEPT
    - 2+ hops (multi-hop / remote transfers): EXCLUDED
    """
    con = populated_test_db
    # Insert 3 houses in different transit topologies:
    # House 1: 100401 (Direct train: 0 hops)
    # House 2: 100402 (1 bus + 1 train: 1 hop)
    # House 3: 100403 (2+ transfers: 2 hops)
    con.execute("""
        INSERT INTO buildings VALUES
        (100401, 'ZH', 'Zürich', 261, 'Directbahnweg', '1', 8001, 'Zürich', 1004, 1020, 1110, 1, 100.0, 2683000.0, 1248000.0, ST_Point(2683000.0, 1248000.0)),
        (100402, 'ZH', 'Küsnacht (ZH)', 154, 'Feederbusweg', '2', 8700, 'Küsnacht ZH', 1004, 1020, 1110, 1, 100.0, 2688000.0, 1240000.0, ST_Point(2688000.0, 1240000.0)),
        (100403, 'ZH', 'Remoteberg', 999, 'Multihopweg', '3', 8999, 'Remoteberg', 1004, 1020, 1110, 1, 100.0, 2695000.0, 1230000.0, ST_Point(2695000.0, 1230000.0));

        CREATE OR REPLACE TABLE transit_stops AS
        SELECT * FROM (
            VALUES
                ('Zürich HB', 'Zug', 2683100.0, 1248050.0, ST_Point(2683100.0, 1248050.0), 5.0, 'Zürich', 2.0, 0, 'Direct train (0 transfers)'),
                ('Küsnacht, Allmend', 'Bus', 2688100.0, 1240050.0, ST_Point(2688100.0, 1240050.0), 10.0, 'Zürich', 15.0, 1, '1 bus + 1 train (1 transfer)'),
                ('Remoteberg, Bergpost', 'Bus', 2695100.0, 1230050.0, ST_Point(2695100.0, 1230050.0), 15.0, 'Zürich', 24.0, 2, '2+ transfers (multi-hop)')
        ) AS t(name, transit_type, gkode, gkodn, geom, cadence_min, nearest_big_city, transit_travel_time_min, transit_hops, transit_route_desc);

        INSERT INTO restaurants VALUES
        (100401, 'Resto 1', 'Directbahnweg', '2', 'Zürich', 2683050.0, 1248020.0, ST_Point(2683050.0, 1248020.0)),
        (100402, 'Resto 2', 'Feederbusweg', '3', 'Küsnacht ZH', 2688050.0, 1240020.0, ST_Point(2688050.0, 1240020.0)),
        (100403, 'Resto 3', 'Multihopweg', '4', 'Remoteberg', 2695050.0, 1230020.0, ST_Point(2695050.0, 1230020.0));

        INSERT INTO supermarkets VALUES
        (100401, 'Migros Direct', 'Migros', 'supermarket', 'Directbahnweg', '10', 8001, 'Zürich', 'ZH', 2683080.0, 1248030.0, ST_Point(2683080.0, 1248030.0)),
        (100402, 'Coop Feeder', 'Coop', 'supermarket', 'Feederbusweg', '11', 8700, 'Küsnacht ZH', 'ZH', 2688080.0, 1240030.0, ST_Point(2688080.0, 1240030.0)),
        (100403, 'Denner Remote', 'Denner', 'supermarket', 'Multihopweg', '12', 8999, 'Remoteberg', 'ZH', 2695080.0, 1230030.0, ST_Point(2695080.0, 1230030.0));

        INSERT INTO gyms VALUES
        (100401, 'Fitness Direct', 'fitness', 'Directweg', '1', 8001, 'Zürich', 'ZH', 2683100.0, 1248020.0, ST_Point(2683100.0, 1248020.0)),
        (100402, 'Fitness Feeder', 'fitness', 'Feederweg', '2', 8700, 'Küsnacht ZH', 'ZH', 2688100.0, 1240020.0, ST_Point(2688100.0, 1240020.0)),
        (100403, 'Fitness Remote', 'fitness', 'Remoteweg', '3', 8999, 'Remoteberg', 'ZH', 2695100.0, 1230020.0, ST_Point(2695100.0, 1230020.0));

        INSERT INTO building_zones VALUES
        (100401, 'Wohnzone', ST_Buffer(ST_Point(2683000.0, 1248000.0), 500.0)),
        (100402, 'Wohnzone', ST_Buffer(ST_Point(2688000.0, 1240000.0), 500.0)),
        (100403, 'Wohnzone', ST_Buffer(ST_Point(2695000.0, 1230000.0), 500.0));

        INSERT INTO land_cover_green VALUES
        (ST_Buffer(ST_Point(2683000.0, 1248000.0), 50.0)),
        (ST_Buffer(ST_Point(2688000.0, 1240000.0), 50.0)),
        (ST_Buffer(ST_Point(2695000.0, 1230000.0), 50.0));

        INSERT INTO transit_quality VALUES
        ('A', ST_Buffer(ST_Point(2683000.0, 1248000.0), 500.0)),
        ('B', ST_Buffer(ST_Point(2688000.0, 1240000.0), 500.0)),
        ('B', ST_Buffer(ST_Point(2695000.0, 1230000.0), 500.0));
    """)

    # Test 1: max_transit_hops = 1 (default: max 1 hop)
    crit_1hop = HousingFilterCriteria(
        max_price_chf=None,
        min_garden_m2=10.0,
        min_green_ratio=0.0,
        max_transit_hops=1,
    )
    execute_housing_pipeline(con, crit_1hop, output_dir=tmp_path / "out_1hop")
    with open(tmp_path / "out_1hop" / "matching_houses.geojson") as f:
        doc1 = json.load(f)
    egids_1hop = {feat["properties"]["egid"] for feat in doc1["features"]}

    assert 100401 in egids_1hop, "Direct train (0 hops) house must be INCLUDED"
    assert 100402 in egids_1hop, "1 bus + 1 train (1 hop) house must be INCLUDED"
    assert 100403 not in egids_1hop, "2+ transfers (2 hops) house must be EXCLUDED under max 1 hop"

    # Verify properties contain transit_hops and transit_route_desc
    house_1 = next(feat for feat in doc1["features"] if feat["properties"]["egid"] == 100401)
    assert house_1["properties"]["transit_hops"] == 0
    assert "Direct" in house_1["properties"]["transit_route_desc"]

    house_2 = next(feat for feat in doc1["features"] if feat["properties"]["egid"] == 100402)
    assert house_2["properties"]["transit_hops"] == 1
    assert "1 bus + 1 train" in house_2["properties"]["transit_route_desc"]

    # Test 2: max_transit_hops = 0 (direct only)
    crit_0hop = HousingFilterCriteria(
        max_price_chf=None,
        min_garden_m2=10.0,
        min_green_ratio=0.0,
        max_transit_hops=0,
    )
    execute_housing_pipeline(con, crit_0hop, output_dir=tmp_path / "out_0hop")
    with open(tmp_path / "out_0hop" / "matching_houses.geojson") as f:
        doc0 = json.load(f)
    egids_0hop = {feat["properties"]["egid"] for feat in doc0["features"]}

    assert 100401 in egids_0hop, "Direct train (0 hops) house must be INCLUDED under max 0 hops"
    assert 100402 not in egids_0hop, "1 bus + 1 train (1 hop) house must be EXCLUDED under max 0 hops"
    assert 100403 not in egids_0hop, "2+ transfers (2 hops) house must be EXCLUDED under max 0 hops"


def test_transit_hops_livability_and_neighborhood_aggregation():
    """Verify transit hops attributes and livability scoring bonus."""
    # Direct transit (0 hops) gets 3.0 pts
    score_direct = calculate_livability_score({
        "median_commute_min": 10.0,
        "median_transit_cadence_min": 10.0,
        "median_transit_hops": 0,
    })
    # 1 hop (1 bus + 1 train) gets 1.5 pts
    score_1hop = calculate_livability_score({
        "median_commute_min": 10.0,
        "median_transit_cadence_min": 10.0,
        "median_transit_hops": 1,
    })
    # 2+ hops gets 0.0 pts
    score_2hops = calculate_livability_score({
        "median_commute_min": 10.0,
        "median_transit_cadence_min": 10.0,
        "median_transit_hops": 2,
    })
    assert score_direct > score_1hop > score_2hops
    assert round(score_direct - score_1hop, 1) == 1.5
    assert round(score_1hop - score_2hops, 1) == 1.5


def test_nearby_restaurants_and_cafes_counts_and_filtering(populated_test_db: duckdb.DuckDBPyConnection, tmp_path: Path):
    """Verify counting and filtering of restaurants+take-away and cafés within 10 min walking (800m)."""
    con = populated_test_db

    # Add specific restaurants and cafes near Bern 100101 (2600100, 1200100) and Zurich 100107 (2683000, 1247000)
    con.execute("""
        CREATE OR REPLACE TABLE restaurants AS
        SELECT * FROM (
            VALUES
                -- Near Bern 100101: 3 dining (1 restaurant, 1 takeaway, 1 burger bistro), 2 cafes
                (1, 'Pizzeria Bern', 'restaurant', 2600150.0, 1200150.0, ST_Point(2600150.0, 1200150.0)),
                (2, 'Asian Take-Away', 'takeaway', 2600200.0, 1200100.0, ST_Point(2600200.0, 1200100.0)),
                (3, 'Burger Bistro', 'fast_food', 2600250.0, 1200150.0, ST_Point(2600250.0, 1200150.0)),
                (4, 'Café Bernese', 'cafe', 2600120.0, 1200120.0, ST_Point(2600120.0, 1200120.0)),
                (5, 'Espresso Bar', 'cafe', 2600300.0, 1200200.0, ST_Point(2600300.0, 1200200.0)),
                -- Far from Bern (> 2000m) -> excluded from counts
                (6, 'Distant Restaurant', 'restaurant', 2603000.0, 1203000.0, ST_Point(2603000.0, 1203000.0)),
                -- Near Zurich 100107: 1 dining, 0 cafes
                (7, 'Seerestaurant ZH', 'restaurant', 2683100.0, 1247000.0, ST_Point(2683100.0, 1247000.0)),
                -- Near Winterthur 100111: 1 dining, 0 cafes
                (8, 'Winti Bistro', 'restaurant', 2697100.0, 1261000.0, ST_Point(2697100.0, 1261000.0)),
                -- Near Thun 100112: 1 dining, 0 cafes
                (9, 'Gasthof Thun', 'restaurant', 2614100.0, 1178000.0, ST_Point(2614100.0, 1178000.0))
        ) AS t(id, name, shop_type, gkode, gkodn, geom);
    """)

    # Baseline run: no minimum counts
    crit = HousingFilterCriteria(
        max_restaurant_walk_min=10.0,
        max_restaurant_dist_m=800.0,
        min_restaurants_nearby=None,
        min_cafes_nearby=None,
    )
    cnt = execute_housing_pipeline(con, crit, output_dir=tmp_path)
    assert cnt >= 3

    # Check parquet counts
    import duckdb as ddb
    pcon = ddb.connect()
    p_df = pcon.execute(f"SELECT egid, num_restaurants_nearby, num_cafes_nearby FROM '{tmp_path}/matching_houses.parquet' WHERE egid IN (100101, 100107) ORDER BY egid").fetchall()
    row_bern = [r for r in p_df if r[0] == 100101][0]
    row_zh = [r for r in p_df if r[0] == 100107][0]
    assert row_bern[1] == 3, f"Expected 3 restaurants/takeaways near Bern 100101, got {row_bern[1]}"
    assert row_bern[2] == 2, f"Expected 2 cafes near Bern 100101, got {row_bern[2]}"
    assert row_zh[1] == 1, f"Expected 1 restaurant near Zurich 100107, got {row_zh[1]}"
    assert row_zh[2] == 0, f"Expected 0 cafes near Zurich 100107, got {row_zh[2]}"

    # Verify GeoJSON export has properties
    with open(tmp_path / "matching_houses.geojson", "r", encoding="utf-8") as f:
        geo_data = json.load(f)
    feats = {f["properties"]["egid"]: f["properties"] for f in geo_data["features"]}
    assert feats[100101]["num_restaurants_nearby"] == 3
    assert feats[100101]["num_cafes_nearby"] == 2
    assert feats[100107]["num_restaurants_nearby"] == 1
    assert feats[100107]["num_cafes_nearby"] == 0

    # Filter with min_cafes_nearby = 1 (Bern matches, Zurich/Winti/Thun excluded)
    crit_cafe = HousingFilterCriteria(
        min_cafes_nearby=1,
    )
    cnt_cafe = execute_housing_pipeline(con, crit_cafe, output_dir=tmp_path / "cafe_filter")
    p_cafe = pcon.execute(f"SELECT egid FROM '{tmp_path}/cafe_filter/matching_houses.parquet'").fetchall()
    egids_cafe = [r[0] for r in p_cafe]
    assert 100101 in egids_cafe
    assert 100107 not in egids_cafe

    # Filter with min_restaurants_nearby = 2 (Bern matches, Zurich/Winti/Thun excluded)
    crit_resto = HousingFilterCriteria(
        min_restaurants_nearby=2,
    )
    cnt_resto = execute_housing_pipeline(con, crit_resto, output_dir=tmp_path / "resto_filter")
    p_resto = pcon.execute(f"SELECT egid FROM '{tmp_path}/resto_filter/matching_houses.parquet'").fetchall()
    egids_resto = [r[0] for r in p_resto]
    assert 100101 in egids_resto
    assert 100107 not in egids_resto






